set -euo pipefail
python3 - <<'PY2'
from pathlib import Path
import subprocess, os, json, time

cfg = Path('/srv/sub2api-80/shared/data/config.yaml')
if not cfg.exists():
    cfg = Path('/home/admin/docker-projects/sub2api/deploy/.env')

text = cfg.read_text()
if cfg.suffix in {'.yaml', '.yml'}:
    in_db = False
    data = {}
    for raw in text.splitlines():
        if not raw.strip() or raw.lstrip().startswith('#'):
            continue
        if not raw.startswith('  '):
            in_db = raw.strip() == 'database:'
            continue
        if in_db and ':' in raw:
            k, v = raw.strip().split(':', 1)
            data[k] = v.strip().strip('"')
    env = os.environ.copy()
    env['PGPASSWORD'] = data['password']
    host = data['host']
    port = data['port']
    user = data['user']
    dbname = data['dbname']
else:
    vals = {}
    for raw in text.splitlines():
        s = raw.strip()
        if not s or s.startswith('#') or '=' not in s:
            continue
        k, v = s.split('=', 1)
        vals[k] = v
    env = os.environ.copy()
    env['PGPASSWORD'] = vals['DATABASE_PASSWORD']
    host = vals['DATABASE_HOST']
    port = vals['DATABASE_PORT']
    user = vals['DATABASE_USER']
    dbname = vals['DATABASE_DBNAME']

key = subprocess.run([
    'psql','-h',host,'-p',str(port),'-U',user,'-d',dbname,'-Atc',
    "select value from settings where key='admin_api_key';"
], env=env, capture_output=True, text=True, check=True).stdout.strip()

payload = {
    'title': '域名迁移与 Windows 设置通知',
    'content': '各位用户好，\n\n由于 JP3 节点已下线，原 `https://sub-lb35.tap365.org` 已迁移承接到当前正式服务。\n\nWindows 客户端 / 工具请统一按以下方式设置：\n- Base URL / 接口地址：`https://api.tap365.org`\n- 若客户端要求填写完整 OpenAI 兼容路径，请填写：`https://api.tap365.org/v1`\n\n补充说明：\n- `sub-lb35.tap365.org` 现已切到当前正式服务，旧域名用户可继续使用\n- 新接入或后续修改配置，建议统一改为 `https://api.tap365.org`\n- 主站入口仍为 `https://sub-lb.tap365.org`\n\n如果本地还命中旧缓存，请重启客户端或等待本地 DNS 缓存刷新后再试。',
    'status': 'active',
    'notify_mode': 'popup',
    'targeting': {},
    'ends_at': int(time.time()) + 86400,
}
Path('/tmp/announcement_sub_lb35_migration.json').write_text(json.dumps(payload, ensure_ascii=False))
post = subprocess.run([
    'curl','--noproxy','*','-sS','-D','-','-o','/tmp/announcement_sub_lb35_migration_resp.json',
    '-H',f'x-api-key: {key}',
    '-H','Content-Type: application/json',
    '-X','POST','https://sub-lb.tap365.org/api/v1/admin/announcements',
    '--data','@/tmp/announcement_sub_lb35_migration.json'
], capture_output=True, text=True, check=True)
print(post.stdout)
print('---BODY---')
print(Path('/tmp/announcement_sub_lb35_migration_resp.json').read_text())
PY2
