"""
OKR模板库 — 建表 + 插入14个CMA标准模板种子数据
"""
import sys
import os
import logging

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from app.database import get_engine, get_session_local, Base
from app.models import OKRTemplate

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("seed_okr_templates")

# ── 14个CMA标准模板 ──
SEED_TEMPLATES = [
    # 💰 财务层（4个）
    {
        "name": "扩大收入规模",
        "description": "通过新市场开拓、新产品线、新客户群实现收入增长",
        "dimension": "finance",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 1,
        "preset_krs": [
            {"name": "营收增长率≥20%", "target_value": "≥20%", "weight": 40, "sort_order": 1},
            {"name": "新客户收入占比≥15%", "target_value": "≥15%", "weight": 30, "sort_order": 2},
            {"name": "客单价提升≥10%", "target_value": "≥10%", "weight": 30, "sort_order": 3},
        ],
    },
    {
        "name": "优化成本结构",
        "description": "通过成本降低和费用管控提升盈利能力",
        "dimension": "finance",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 2,
        "preset_krs": [
            {"name": "毛利率提升≥3%", "target_value": "≥3%", "weight": 40, "sort_order": 1},
            {"name": "管理费用率≤15%", "target_value": "≤15%", "weight": 30, "sort_order": 2},
            {"name": "销售费用率≤10%", "target_value": "≤10%", "weight": 30, "sort_order": 3},
        ],
    },
    {
        "name": "提升资产效率",
        "description": "提高资产周转速度，释放沉淀资金",
        "dimension": "finance",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 3,
        "preset_krs": [
            {"name": "库存周转天数≤45天", "target_value": "≤45天", "weight": 34, "sort_order": 1},
            {"name": "应收账款周转天数≤45天", "target_value": "≤45天", "weight": 33, "sort_order": 2},
            {"name": "总资产周转率≥1.0", "target_value": "≥1.0", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "保障现金流安全",
        "description": "确保经营现金流为正，防范流动性风险",
        "dimension": "finance",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 4,
        "preset_krs": [
            {"name": "现金比率≥20%", "target_value": "≥20%", "weight": 34, "sort_order": 1},
            {"name": "经营现金流为正", "target_value": "为正", "weight": 33, "sort_order": 2},
            {"name": "自由现金流≥0", "target_value": "≥0", "weight": 33, "sort_order": 3},
        ],
    },
    # 👥 客户层（3个）
    {
        "name": "产品领先",
        "description": "提供行业最优的产品质量和功能",
        "dimension": "customer",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 5,
        "preset_krs": [
            {"name": "产品合格率≥99%", "target_value": "≥99%", "weight": 34, "sort_order": 1},
            {"name": "NPS净推荐值≥60", "target_value": "≥60", "weight": 33, "sort_order": 2},
            {"name": "市场份额提升≥2%", "target_value": "≥2%", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "客户亲密",
        "description": "建立深度客户关系，提升客户粘性",
        "dimension": "customer",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 6,
        "preset_krs": [
            {"name": "客户满意度≥90%", "target_value": "≥90%", "weight": 34, "sort_order": 1},
            {"name": "大客户留存率≥95%", "target_value": "≥95%", "weight": 33, "sort_order": 2},
            {"name": "服务响应时间≤2小时", "target_value": "≤2小时", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "卓越运营",
        "description": "以最优的价格和最高的便利性服务客户",
        "dimension": "customer",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 7,
        "preset_krs": [
            {"name": "价格竞争力行业TOP3", "target_value": "TOP3", "weight": 34, "sort_order": 1},
            {"name": "按时交付率≥98%", "target_value": "≥98%", "weight": 33, "sort_order": 2},
            {"name": "客户投诉率≤1%", "target_value": "≤1%", "weight": 33, "sort_order": 3},
        ],
    },
    # ⚙️ 流程层（4个）
    {
        "name": "运营高效顺畅",
        "description": "优化供应链和交付流程，提升运营效率",
        "dimension": "process",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 8,
        "preset_krs": [
            {"name": "交付及时率≥95%", "target_value": "≥95%", "weight": 34, "sort_order": 1},
            {"name": "库存周转≤45天", "target_value": "≤45天", "weight": 33, "sort_order": 2},
            {"name": "流程自动化率≥30%", "target_value": "≥30%", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "客户管理有序",
        "description": "建立标准化客户管理流程",
        "dimension": "process",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 9,
        "preset_krs": [
            {"name": "新客获取成本下降≥10%", "target_value": "≥10%", "weight": 34, "sort_order": 1},
            {"name": "客户流失率≤5%", "target_value": "≤5%", "weight": 33, "sort_order": 2},
            {"name": "客户线索转化率≥20%", "target_value": "≥20%", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "创新驱动增长",
        "description": "通过产品和服务创新驱动业务增长",
        "dimension": "process",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 10,
        "preset_krs": [
            {"name": "新产品收入占比≥15%", "target_value": "≥15%", "weight": 34, "sort_order": 1},
            {"name": "研发投入占比≥5%", "target_value": "≥5%", "weight": 33, "sort_order": 2},
            {"name": "年度创新提案≥12项", "target_value": "≥12项", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "合规稳健运营",
        "description": "确保合规运营，防范法律和税务风险",
        "dimension": "process",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 11,
        "preset_krs": [
            {"name": "合规事件0起", "target_value": "0起", "weight": 34, "sort_order": 1},
            {"name": "审计通过率100%", "target_value": "100%", "weight": 33, "sort_order": 2},
            {"name": "税务申报及时率100%", "target_value": "100%", "weight": 33, "sort_order": 3},
        ],
    },
    # 📚 学习层（3个）
    {
        "name": "团队能力升级",
        "description": "提升员工核心技能和关键岗位胜任度",
        "dimension": "learning",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 12,
        "preset_krs": [
            {"name": "关键岗位培训完成率100%", "target_value": "100%", "weight": 34, "sort_order": 1},
            {"name": "认证持有率≥80%", "target_value": "≥80%", "weight": 33, "sort_order": 2},
            {"name": "人均培训时长≥40小时/年", "target_value": "≥40小时/年", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "数字系统赋能",
        "description": "通过数字化系统提升工作效率",
        "dimension": "learning",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 13,
        "preset_krs": [
            {"name": "系统覆盖率≥90%", "target_value": "≥90%", "weight": 34, "sort_order": 1},
            {"name": "数据自动化率≥70%", "target_value": "≥70%", "weight": 33, "sort_order": 2},
            {"name": "报表自动生成率≥80%", "target_value": "≥80%", "weight": 33, "sort_order": 3},
        ],
    },
    {
        "name": "组织协同对齐",
        "description": "建立高绩效文化和战略共识",
        "dimension": "learning",
        "layer": "level1",
        "industry_tag": "general",
        "source": "system",
        "sort_order": 14,
        "preset_krs": [
            {"name": "员工满意度≥85%", "target_value": "≥85%", "weight": 34, "sort_order": 1},
            {"name": "战略认知度≥80%", "target_value": "≥80%", "weight": 33, "sort_order": 2},
            {"name": "跨部门协作评分≥4分", "target_value": "≥4分", "weight": 33, "sort_order": 3},
        ],
    },
]


def ensure_table():
    """确保 okr_templates 表存在"""
    Base.metadata.create_all(bind=get_engine())
    logger.info("表 okr_templates 已就绪")


def seed_templates():
    """插入种子数据（如果表为空）"""
    session = get_session_local()()
    try:
        existing = session.query(OKRTemplate).filter(OKRTemplate.source == "system").count()
        if existing > 0:
            logger.info(f"已有 {existing} 条系统模板，跳过种子数据")
            return
        for item in SEED_TEMPLATES:
            t = OKRTemplate(**item)
            session.add(t)
        session.commit()
        logger.info(f"✔ 已插入 {len(SEED_TEMPLATES)} 条 CMA 标准模板")
    except Exception as e:
        session.rollback()
        logger.error(f"种子数据插入失败: {e}")
        raise
    finally:
        session.close()


if __name__ == "__main__":
    ensure_table()
    seed_templates()
    logger.info("OKR模板库初始化完成")
