"""把现有 data/queries/demo.json + search_results.json 导入 data/app.db。

一次性迁移 / 重导用。run_id 用固定名（demo / search-demo），重导幂等覆盖。
用法：PYTHONPATH=. python scripts/import_to_db.py
"""
from __future__ import annotations

import json
import time
from pathlib import Path

from acquisition import store

ROOT = Path(__file__).resolve().parent.parent
DEMO = ROOT / "data" / "queries" / "demo.json"
SEARCH = ROOT / "data" / "queries" / "search_results.json"


def main() -> None:
    ts = int(time.time())
    conn = store.connect()
    try:
        if DEMO.exists():
            demo = json.loads(DEMO.read_text("utf-8"))
            for key in ("tactic1", "tactic2", "tactic3", "tactic4"):
                t = demo.get(key) or {}
                items = t.get("items") or []
                if not items:
                    continue
                n = store.insert_queries(conn, "demo", t.get("name", key), items, ts=ts)
                print(f"queries[{t.get('name', key)}]: {n} 条")
        if SEARCH.exists():
            recs = json.loads(SEARCH.read_text("utf-8"))
            n = store.insert_search_results(conn, "search-demo", recs, ts=ts)
            print(f"search_results: {n} 行（{len(recs)} 条 query × 平台拍平）")
        print("runs:", [r["run_id"] for r in store.list_runs(conn)])
    finally:
        conn.close()


if __name__ == "__main__":
    main()
