#!/usr/bin/env python3
"""补充非财务KPI预算数据 — 客户/流程/学习维度
运行: python3 scripts/seed_nonfinance_budget.py
"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.database import get_session_local
from app.models import KPIDefinition, BudgetPlan
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger("seed_nonfinance")

def seed():
    db = get_session_local()()
    try:
        kpi_map = {k.kpi_code: k.id for k in db.query(KPIDefinition).all()}
        codes = ["C_SATISFACTION", "C_NEW_CLIENTS", "P_DELIVERY", "P_BUG_RATE", "L_TRAINING", "L_EMPLOYEE_SAT"]
        # 年度预算值
        annual_budget = {
            "C_SATISFACTION": 92, "C_NEW_CLIENTS": 120,
            "P_DELIVERY": 95, "P_BUG_RATE": 2,
            "L_TRAINING": 90, "L_EMPLOYEE_SAT": 85,
        }
        cnt = 0
        existing = set((r.kpi_id, r.period) for r in db.query(BudgetPlan).all())
        for code in codes:
            kid = kpi_map.get(code)
            if not kid: continue
            annual = annual_budget[code]
            for month in range(1, 13):
                if (kid, f"2026-{month:02d}") in existing:
                    continue
                db.add(BudgetPlan(
                    kpi_id=kid, period=f"2026-{month:02d}",
                    budget_value=annual if code != "C_NEW_CLIENTS" else annual / 12,
                    budget_year=2026, budget_month=month,
                    version="v1.0", status="active",
                ))
                cnt += 1
        db.commit()
        logger.info(f"✅ 补充非财务预算: {cnt}条")
        logger.info(f"📊 预算总数: {db.query(BudgetPlan).count()}条")
    except Exception as e:
        db.rollback()
        logger.error(f"❌ 失败: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    seed()
