"""恢复 51 本 curated 期刊 → 跑 seed"""
import json, os
from datetime import datetime
from sqlalchemy import create_engine, text

DB_URL = os.environ.get("SEED_DB_URL") or "postgresql://scilit:scilit_dev@localhost:5432/scilit"
engine = create_engine(DB_URL, pool_pre_ping=True)

with engine.connect() as conn:
    conn.execute(text("TRUNCATE TABLE global_journals CASCADE"))
    # 从备份 JSON 恢复
    with open("/tmp/original_51_journals.json") as f:
        journals = json.load(f)
    now = datetime.utcnow()
    for j in journals:
        conn.execute(
            text("""INSERT INTO global_journals (id, name, issn, eissn, tier, impact_factor, publisher, article_count, is_active, created_at, updated_at)
                     VALUES (:id, :name, :issn, :eissn, :tier, :if, :pub, :ac, True, :now, :now)"""),
            {"id": j["id"], "name": j["name"], "issn": j["issn"], "eissn": j["eissn"],
             "tier": j["tier"], "if": j["impact_factor"], "pub": j["publisher"],
             "ac": j["article_count"] or 0, "now": now},
        )
    conn.commit()
    cnt = conn.execute(text("SELECT COUNT(*) FROM global_journals")).scalar()
    print(f"Restored {cnt} journals.")
