# -*- 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

receivers=[{'name':n} for n in ['fallback','normal','critical']]
broad={'matchers':['service="gateway"'],'receiver':'normal'}
strict={'matchers':['service="gateway"','severity="critical"'],'receiver':'critical'}
def config(routes): return {'route':{'receiver':'fallback','routes':routes},'receivers':receivers}
before=amrun(config([broad,strict]),['config','routes','test','--verify.receivers=normal','service=gateway','severity=critical'])
after=amrun(config([strict,broad]),['config','routes','test','--verify.receivers=critical','service=gateway','severity=critical'])
ordinary=amrun(config([strict,broad]),['config','routes','test','--verify.receivers=normal','service=gateway','severity=warning'])
fallback=amrun(config([strict,broad]),['config','routes','test','--verify.receivers=fallback','service=other','severity=critical'])
emit(before='normal',after='critical',ordinary='normal',fallback='fallback',raw=[before,after,ordinary,fallback])
