#!/usr/bin/env python3 import argparse from contextlib import closing from pathlib import Path import os import re import sqlite3 import sys import time from runtime_config import gateway_db_path GW_DB = gateway_db_path() BOT_SRC = os.environ.get("IISHKO_BOT_SOURCE") or str(Path(__file__).with_name("grok_bot.py")) BOT_SRC_FALLBACK = BOT_SRC TIER_GROUPS = ("t1", "t2", "t3", "t4") LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id " "WHERE a.model=? AND a.enabled=1 AND c.status=1 " "AND instr(',' || replace(c.models,' ','') || ',', ',' || a.model || ',')>0") # [FIX-2410] containment как в repair def _read_src(path): try: with open(path, encoding="utf-8") as f: return f.read() except OSError as e: print(time.strftime("%F %T"), "cannot read", path, str(e)[:120], flush=True) return "" def _parse_tiers(src): m = re.search(r"^TIER_MODELS\s*=\s*\{(.*?)^\s*\}", src, re.S | re.M) if not m: return {} body = re.sub(r"#[^\n]*", "", m.group(1)) tiers = {} for tm in re.finditer(r"(\d+)\s*:\s*\[(.*?)\]", body, re.S): names = re.findall(r"""["']([A-Za-z0-9._/\-]+)["']""", tm.group(2)) if names: tiers[int(tm.group(1))] = sorted(set(names)) return tiers def catalog_tiers(path=None): """Read tier declarations without importing or starting the bot.""" paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK) for p in paths: tiers = _parse_tiers(_read_src(p)) if tiers: return tiers return {} def catalog_models(tiers): """Union моделей каталога (для отчёта dark).""" return sorted({m for ms in tiers.values() for m in ms}) def repair_abilities(con, tiers): if not tiers: return 0 models = catalog_models(tiers) order = [n for n in sorted(tiers) if 1 <= n <= 4] if not models or not order: return 0 def ph(n): return ",".join(["?"] * n) params = list(models) + list(TIER_GROUPS) gate_parts = ['abilities."group" NOT IN (' + ph(len(TIER_GROUPS)) + ')'] for n in order: cum = [m for i in order if i <= n for m in tiers[i]] if not cum: continue gate_parts.append('(abilities."group"=? AND abilities.model IN (' + ph(len(cum)) + '))') params.append("t" + str(n)) params.extend(cum) # [FIX-2410] Нормализация containment: c.models может быть «m1, m2» с пробелами — sql = ("UPDATE abilities SET enabled=1 WHERE enabled=0 AND model IN (" + ph(len(models)) + ") " + "AND EXISTS (SELECT 1 FROM channels c WHERE c.id=abilities.channel_id " "AND c.status=1 AND instr(',' || replace(c.models,' ','') || ',', " "',' || abilities.model || ',')>0) " + "AND (" + " OR ".join(gate_parts) + ")") return con.execute(sql, params).rowcount def main(argv=None): parser = argparse.ArgumentParser( description="Check route availability; read-only unless --apply is explicit.") parser.add_argument("--db", help="absolute path to an existing New API SQLite database") parser.add_argument("--source", help="absolute path to bot source containing TIER_MODELS") parser.add_argument("--apply", action="store_true", help="explicitly re-enable matching abilities") args = parser.parse_args(argv) if args.apply and (not args.db or not args.source): parser.error("--apply requires explicit --db and --source") db, source = Path(args.db or GW_DB), Path(args.source or BOT_SRC) for label, path in (("database", db), ("source", source)): if not path.is_absolute() or not path.is_file(): parser.error(label + " must be an absolute path to an existing file") tiers = catalog_tiers(str(source)) if not tiers: print("No catalog tiers parsed; no database changes made.", flush=True) return 1 models = catalog_models(tiers) mode = "rw" if args.apply else "ro" try: with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=" + mode, uri=True, timeout=10)) as con: fixed = 0 with con: if args.apply: fixed = repair_abilities(con, tiers) dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]] except sqlite3.Error as exc: print("Database check failed: " + type(exc).__name__, file=sys.stderr) return 2 print("mode=%s catalog=%d re-enabled=%d dark=%s" % ("apply" if args.apply else "dry-run", len(models), fixed, ",".join(dark) if dark else "none"), flush=True) return 0 if __name__ == "__main__": sys.exit(main())