"""给老的「多轴正交组合」query 加一层创作筛选（query_filter.txt）。

读 DB 里 method=多轴正交组合 的每条 query，批量过 filter，把 keep + filter_reason 写回各自的
axes JSON（前端据此显示 留/排除）。不重生成、不动搜索结果，纯就地打标。
用法：PYTHONPATH=. CK_ENV_FILE=.env python scripts/filter_multiaxis.py [method]
"""
from __future__ import annotations

import json
import sys

from acquisition import store
from acquisition.query_filter import filter_queries
from core.config import Settings

METHOD = sys.argv[1] if len(sys.argv) > 1 else "多轴正交组合"


def main() -> None:
    settings = Settings.from_env()
    conn = store.connect()
    try:
        rows = conn.execute("SELECT id, query, axes FROM queries WHERE method=?", (METHOD,)).fetchall()
        if not rows:
            print(f"DB 里没有 method={METHOD} 的 query")
            return
        queries = [r["query"] for r in rows]
        print(f"{METHOD}: {len(queries)} 条 → 过滤中…")
        verdicts = filter_queries(queries, settings)
        kept = 0
        for r, v in zip(rows, verdicts):
            axes = json.loads(r["axes"] or "{}")
            axes["keep"] = v["keep"]
            axes["filter_reason"] = v["reason"]
            conn.execute("UPDATE queries SET axes=? WHERE id=?",
                         (json.dumps(axes, ensure_ascii=False), r["id"]))
            kept += 1 if v["keep"] else 0
        conn.commit()
        print(f"完成：保留 {kept} / {len(queries)}（排除 {len(queries) - kept}）")
    finally:
        conn.close()


if __name__ == "__main__":
    main()
