# -*- coding: utf-8 -*-
"""只操作本程序创建的临时对象；全部数据为合成样本。"""
import os, sys, json, sqlite3, tempfile, pathlib, subprocess, time, socket, stat
from pathlib import Path
def emit(**kw):
    print(json.dumps(kw, ensure_ascii=False, sort_keys=True))

import shutil
AMTOOL=os.environ.get('AMTOOL') or shutil.which('amtool')
assert AMTOOL, '请安装官方Alertmanager 0.28.1的amtool，加入PATH或设置AMTOOL'
def amrun(config,args):
    with tempfile.TemporaryDirectory(prefix='ywebs-next132-b2-am-') as d:
        p=Path(d)/'alertmanager.yml'; p.write_text(json.dumps(config),encoding='utf-8')
        command=[AMTOOL]+args+([str(p)] if args==['check-config'] else ['--config.file='+str(p)])
        r=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True)
        assert r.returncode==0,r.stdout
        return r.stdout

config={'route':{'receiver':'demo'},'receivers':[{'name':'demo'}],'inhibit_rules':[{'source_matchers':['severity="critical"','tenant!=""'],'target_matchers':['severity="warning"','tenant!=""'],'equal':['service','tenant']}]}
checked=amrun(config,['check-config'])
source={'service':'gateway','severity':'critical','tenant':'A'}
targets=[{'service':'gateway','severity':'warning','tenant':'A'},{'service':'gateway','severity':'warning','tenant':'B'},{'service':'gateway','severity':'warning'}]
def equal(a,b,keys): return all(a.get(k,'')==b.get(k,'') for k in keys)
unsafe=[equal(source,x,['service']) for x in targets]
scoped=[bool(source.get('tenant') and x.get('tenant')) and equal(source,x,['service','tenant']) for x in targets]
missing_pair_equal=equal({'service':'gateway'},{'service':'gateway'},['service','tenant'])
assert unsafe==[True,True,True] and scoped==[True,False,False] and missing_pair_equal
emit(unsafe=unsafe,scoped=scoped,both_missing_equal=missing_pair_equal,config_check=checked,scope='等值标签参考模型，不是完整抑制引擎')
