"""
插入包含完整评分字段的 Mock 数据
"""
import asyncio
import httpx
import json
import uuid
import random

COZE_PAT_TOKEN = 'pat_nd1wU47WyPS9GCIyJ1clnH8h1WOQXGrYELX8w73TnSZaYbFdYD4swIhzcETBUbfT'
WORKFLOW_ID = '7597376294612107318'

CANDIDATES = [
    {'name': '周雪琴', 'base_score': 88},
    {'name': '陈美华', 'base_score': 75},
    {'name': '林婷婷', 'base_score': 92},
    {'name': '黄丽萍', 'base_score': 65},
    {'name': '吴晓燕', 'base_score': 82},
]


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


def gen_score(base: int, variance: int = 10) -> int:
    return max(50, min(100, base + random.randint(-variance, variance)))


def get_level(score: int) -> str:
    if score >= 85:
        return "优秀"
    elif score >= 70:
        return "良好"
    else:
        return "一般"


def escape_sql(s: str) -> str:
    return s.replace("'", "''")


async def main():
    print('插入包含完整评分的 Mock 数据...')
    print('=' * 50)
    
    for idx, c in enumerate(CANDIDATES, 1):
        session_id = f'MOCK_{uuid.uuid4().hex[:8].upper()}'
        base = c['base_score']
        name = c['name']
        
        # 生成各维度分数
        skill_score = gen_score(base)
        concept_score = gen_score(base)
        competency_score = gen_score(base)
        avg_score = round((skill_score + concept_score + competency_score) / 3)
        
        # 生成报告
        skill_level = get_level(skill_score)
        concept_level = get_level(concept_score)
        competency_level = get_level(competency_score)
        
        skill_report = f"销售技能评估：该候选人展现出{skill_level}的销售技巧。得分 {skill_score} 分。"
        concept_report = f"销售观念评估：候选人对销售工作的认知{concept_level}。得分 {concept_score} 分。"
        competency_report = f"综合素质评估：候选人的学习能力和抗压能力{competency_level}。得分 {competency_score} 分。"
        
        recommend = "强烈推荐录用" if avg_score >= 85 else ("建议录用" if avg_score >= 70 else "建议观察")
        
        final_report = f"""## 面试评估报告
**候选人**: {name}
**综合评分**: {avg_score}/100

### 各维度评分
- 销售技能: {skill_score}分
- 销售观念: {concept_score}分
- 综合素质: {competency_score}分

### 建议
{recommend}
"""
        
        # 完整的 INSERT 语句
        sql = f"""INSERT INTO ci_interview_assessments (
            session_id, candidate_name, current_stage,
            sales_skill_score, sales_skill_report,
            sales_concept_score, sales_concept_report,
            competency_score, competency_report,
            final_score_report
        ) VALUES (
            '{session_id}', '{name}', 'completed',
            '{skill_score}', '{escape_sql(skill_report)}',
            '{concept_score}', '{escape_sql(concept_report)}',
            '{competency_score}', '{escape_sql(competency_report)}',
            '{escape_sql(final_report)}'
        )"""
        
        result = await execute_sql(sql, 'assessments')
        status = '✅' if result.get('code') == 0 else f"❌ code={result.get('code')}"
        print(f'{idx}. {name}: 技能{skill_score} 观念{concept_score} 素质{competency_score} -> {status}')
        
        # 插入对话记录
        dialogues = [
            ('销售技能', '请描述一次成功的销售经历', '我曾经成功说服一位犹豫的客户购买了我们的高端护肤套装，通过了解她的肤质问题，提供了针对性的方案。'),
            ('销售观念', '您认为什么是好的销售', '好的销售是真正帮助客户解决问题，建立长期信任关系，而不是一次性交易。'),
            ('综合素质', '遇到困难时您如何应对', '我会先冷静分析问题的原因，制定解决方案，并保持积极的心态去执行。'),
        ]
        
        for j, (stage, q, a) in enumerate(dialogues, 1):
            log_id = f'LOG_{session_id}_{j:02d}'
            log_sql = f"""INSERT INTO ci_interview_logs (
                log_id, session_id, stage, round, ai_question, user_answer, log_type
            ) VALUES (
                '{log_id}', '{session_id}', '{stage}', '{j}',
                '{escape_sql(q)}', '{escape_sql(a)}', 'interview'
            )"""
            await execute_sql(log_sql, 'logs')
        
        await asyncio.sleep(0.3)
    
    print('=' * 50)
    print('✅ 完成！')


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