"""
插入完整模拟面试数据（8 条候选人 + 对话记录）
"""
import asyncio
import httpx
import json
import uuid

COZE_API_BASE = "https://api.coze.cn"
COZE_PAT_TOKEN = "pat_nd1wU47WyPS9GCIyJ1clnH8h1WOQXGrYELX8w73TnSZaYbFdYD4swIhzcETBUbfT"
WORKFLOW_ID = "7597376294612107318"

# 候选人数据
CANDIDATES = [
    {"name": "张小美", "skill": 85, "concept": 82, "comp": 88, "status": "completed", "risk": ""},
    {"name": "李明辉", "skill": 72, "concept": 70, "comp": 75, "status": "completed", "risk": ""},
    {"name": "王晓丽", "skill": 92, "concept": 90, "comp": 95, "status": "completed", "risk": ""},
    {"name": "陈建国", "skill": 65, "concept": 60, "comp": 68, "status": "completed", "risk": "面试中表现紧张，需关注"},
    {"name": "刘芳芳", "skill": 78, "concept": 75, "comp": 80, "status": "completed", "risk": ""},
    {"name": "赵大伟", "skill": 55, "concept": 52, "comp": 58, "status": "completed", "risk": "销售经验不足，需重点培训"},
    {"name": "孙婷婷", "skill": 88, "concept": 85, "comp": 90, "status": "in_progress", "risk": ""},
    {"name": "周志强", "skill": 45, "concept": 42, "comp": 48, "status": "completed", "risk": "不建议录用，综合能力较弱"},
]

# 简历模板
RESUMES = [
    "3年销售经验，曾在某知名医美机构担任销售顾问，业绩连续12个月达成率超过120%。",
    "5年美容行业从业经验，持有高级美容师证书。性格开朗，沟通能力强。",
    "应届毕业生，市场营销专业，在校期间有丰富的社团活动经验。对医美行业充满热情。",
    "2年电商销售经验，熟悉线上运营和客户服务。希望转型到线下医美销售领域。",
]

# 对话模板
DIALOGUES = [
    ("开场", "你好，请先做个自我介绍", "面试官您好，我是{name}，很高兴参加这次面试。我之前有销售相关经验，对轻医美行业很感兴趣。"),
    ("技能", "请介绍你常用的销售技巧", "我主要采用顾问式销售方法，先通过沟通了解客户的真实需求，然后针对性地推荐适合的产品或服务。"),
    ("技能", "遇到客户异议时如何处理", "首先我会认真倾听客户的顾虑，表示理解。然后用专业知识解答疑问，必要时提供案例或数据支持。"),
    ("观念", "你如何看待销售这份工作", "我认为销售不仅是卖产品，更是帮助客户解决问题。好的销售是客户的顾问和朋友。"),
    ("素质", "你的职业规划是什么", "短期希望成为一名优秀的销售顾问，中期目标是带领团队，长期希望在医美行业有深入发展。"),
]

async def execute_sql(sql: str, table: str) -> dict:
    headers = {
        "Authorization": f"Bearer {COZE_PAT_TOKEN}",
        "Content-Type": "application/json"
    }
    input_json = json.dumps({"table": table, "sql": sql}, ensure_ascii=False)
    
    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.post(
            f"{COZE_API_BASE}/v1/workflow/run",
            headers=headers,
            json={"workflow_id": WORKFLOW_ID, "parameters": {"input": input_json}}
        )
        return response.json()

def escape(s):
    """转义 SQL 特殊字符"""
    return s.replace("'", "''") if s else ""

async def main():
    print("=" * 60)
    print("插入完整模拟数据 (8 条候选人)")
    print("=" * 60)
    
    for idx, c in enumerate(CANDIDATES):
        session_id = f"MOCK_{uuid.uuid4().hex[:8].upper()}"
        resume = RESUMES[idx % len(RESUMES)]
        
        # 生成报告
        skill_report = f"销售技能评估：候选人在产品介绍和需求挖掘方面{'表现出色' if c['skill'] >= 80 else '有待提升'}。得分：{c['skill']}分"
        concept_report = f"销售观念评估：对销售工作{'有正确认知' if c['concept'] >= 70 else '认识不够深入'}。得分：{c['concept']}分"
        comp_report = f"综合素质评估：学习能力{'强' if c['comp'] >= 80 else '一般'}，抗压能力{'好' if c['comp'] >= 75 else '需加强'}。得分：{c['comp']}分"
        
        # 1. 插入 Assessment
        sql1 = f"""INSERT INTO ci_interview_assessments (
            session_id, candidate_name, resume_text, current_stage,
            sales_skill_score, sales_concept_score, competency_score,
            sales_skill_report, sales_concept_report, competency_report,
            motivation_summary, risk_warning, growth_plan, ref_check_list
        ) VALUES (
            '{session_id}', '{c["name"]}', '{escape(resume)}', '{c["status"]}',
            '{c["skill"]}', '{c["concept"]}', '{c["comp"]}',
            '{escape(skill_report)}', '{escape(concept_report)}', '{escape(comp_report)}',
            '候选人对轻医美行业表现出兴趣，希望长期发展。',
            '{escape(c["risk"])}',
            '建议入职后进行系统培训，由资深顾问带教。',
            '建议背调：确认任职时间、业绩数据、离职原因。'
        )"""
        
        print(f"\n[{idx+1}/8] {c['name']} (session: {session_id})")
        result = await execute_sql(sql1, "assessments")
        
        if result.get('code') != 0:
            print(f"    ❌ Assessment 失败: {result.get('msg')}")
            continue
        
        print(f"    ✅ Assessment: {c['skill']}/{c['concept']}/{c['comp']}")
        
        # 2. 插入对话记录
        for d_idx, (stage, q, a) in enumerate(DIALOGUES, 1):
            log_id = f"LOG_{session_id}_{d_idx:02d}"
            answer = a.replace("{name}", c["name"])
            
            sql2 = f"""INSERT INTO ci_interview_logs (
                log_id, session_id, stage, round, ai_question, user_answer, log_type
            ) VALUES (
                '{log_id}', '{session_id}', '{stage}', '{d_idx}', 
                '{escape(q)}', '{escape(answer)}', 'interview'
            )"""
            
            result = await execute_sql(sql2, "logs")
            if result.get('code') != 0:
                print(f"    ⚠️ 对话{d_idx}: {result.get('msg')[:30]}")
        
        print(f"    ✅ 对话: {len(DIALOGUES)} 条")
    
    print("\n" + "=" * 60)
    print("✅ 完成！共插入 8 条候选人 + 40 条对话记录")
    print("=" * 60)

if __name__ == "__main__":
    asyncio.run(main())
