"""
KR完整修复(2026-08-27) 迁移脚本:
读 strategic_maps.dimensions JSON → 同步 objectives + krs 表
复用 maps.py 的 _sync_objectives_krs 逻辑
"""
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from app.database import get_session_local
from app.models import StrategicMap, KR, Objective
from app.api.maps import _sync_objectives_krs


def migrate():
    db = get_session_local()()
    try:
        maps = db.query(StrategicMap).all()
        total_kr = 0
        for m in maps:
            before = db.query(KR).filter(KR.entity_id == (m.entity_id or 1)).count()
            _sync_objectives_krs(m, db)
            after = db.query(KR).filter(KR.entity_id == (m.entity_id or 1)).count()
            total_kr += (after - before)
            print(f"地图[{m.id}] {m.title} (entity={m.entity_id}): KR {before} → {after}")
        # 汇总
        print(f"\n迁移完成: krs表总记录 = {db.query(KR).count()}")
        print(f"objectives表总记录 = {db.query(Objective).count()}")
        # 显示样本
        rows = db.query(KR).order_by(KR.id).limit(5).all()
        for kr in rows:
            print(f"  KR#{kr.id}: {kr.title} | op={kr.operator} | target={kr.target_value} | weight={kr.weight} | obj={kr.objective_id}")
    finally:
        db.close()


if __name__ == "__main__":
    migrate()
