# =============================================================================
# 企微IT智能服务台 — 会话 Mock 数据填充脚本
# =============================================================================
# 说明：往 SQLite 数据库 conversations 表写入 15 条模拟会话
# 用法：cd backend && ..\venv\Scripts\python.exe seed_conversations.py
# =============================================================================

import sqlite3
from datetime import datetime, timezone, timedelta
import json
import uuid

DB_PATH = r"C:\Users\simon\wecom_it_smart_desk\backend\it_smart_desk.db"

# 当前时间（UTC）
NOW = datetime.now(tz=timezone.utc)
ISO = lambda dt: dt.isoformat()

def make_conv(cid, user_id, name, dept, position, level,
             status, is_vip, is_pinned, is_todo,
             urgency, tags, assigned_agent, impact, is_blocking, emotion,
             last_summary, mins_ago):
    """构造一条会话记录（tuple）"""
    seq = int(cid.split("-")[1])
    hours_ago = max(0, 48 - seq * 3)
    created = NOW - timedelta(hours=hours_ago)
    updated = NOW - timedelta(minutes=mins_ago) if mins_ago else created
    last_msg = NOW - timedelta(minutes=mins_ago) if mins_ago else None

    return (
        cid,                           # id
        "ww1234567890",                # corp_id
        user_id,                      # employee_id
        name,                          # employee_name
        dept,                          # department
        position,                      # position
        level,                         # level
        status,                        # status
        1 if is_vip else 0,           # is_vip
        1 if is_pinned else 0,       # is_pinned
        1 if is_todo else 0,         # is_todo
        urgency,                       # urgency_score
        json.dumps(tags, ensure_ascii=False),  # tags (JSON)
        assigned_agent,                 # assigned_agent_id
        json.dumps([], ensure_ascii=False),  # collaborating_agent_ids
        0,                             # ai_substantive_reply_count
        impact,                        # impact_scope
        1 if is_blocking else 0,      # is_blocking
        emotion,                       # emotion_state
        None,                          # dify_conversation_id
        ISO(last_msg) if last_msg else None,  # last_message_at
        last_summary,                  # last_message_summary
        ISO(created),                  # created_at
        ISO(updated),                  # updated_at
    )

rows = [
    # ── 排队中（queued）────
    make_conv("conv-001", "user-001", "张伟", "财务部", "经理", "P6",
              "queued", False, False, False,
              5, {"hand_raise": True, "emotion": "urgent"},
              None, 0, False, "urgent",
              "VPN 连不上，报错 Error 691，今天要急着报税！", 5),

    make_conv("conv-002", "user-002", "李娜", "设计部", "设计师", "P5",
              "queued", False, False, True,
              3, {"emotion": "worried"},
              None, 0, False, "worried",
              "PS 2026 安装后一直闪退，急需用", 12),

    make_conv("conv-003", "user-003", "王强", "市场部", "总监", "P7",
              "queued", True, False, False,
              4, {"hand_raise": True, "need_intervene": True},
              None, 8, True, "angry",
              "邮箱满了，发送失败，影响了3个客户的报价单！", 1),

    make_conv("conv-004", "user-004", "刘芳", "人事部", "HRBP", "P6",
              "queued", False, False, False,
              2, {},
              None, 0, False, "neutral",
              "OA 系统白屏，其他同事也有同样问题", 30),

    make_conv("conv-005", "user-005", "陈明", "研发部", "高级工程师", "P7",
              "queued", True, False, False,
              4, {"need_intervene": True},
              None, 2, True, "urgent",
              "生产数据库只读权限申请，今天上线要用", 8),

    # ── 服务中（serving）────
    make_conv("conv-006", "user-006", "赵敏", "市场部", "专员", "P4",
              "serving", False, False, False,
              3, {"emotion": "worried"},
              "agent-001", 0, False, "worried",
              "打印机驱动装好了，但是打印出来是乱码", 60),

    make_conv("conv-007", "user-007", "周婷", "行政部", "行政主管", "P5",
              "serving", False, True, False,
              2, {},
              "agent-001", 0, False, "neutral",
              "会议室投影仪怎么切换到HDMI模式？下午有客户来访", 120),

    make_conv("conv-008", "user-008", "吴婷", "人事部", "薪酬经理", "P6",
              "serving", False, False, True,
              3, {"emotion": "angry"},
              "agent-001", 1, False, "angry",
              "新员工入职的笔记本磁盘只有 256G，完全不够用", 45),

    make_conv("conv-009", "user-009", "刘军", "销售部", "大区经理", "P7",
              "serving", True, False, False,
              4, {"hand_raise": True},
              "agent-001", 5, True, "urgent",
              "CRM 系统卡死，正在和客户通话，急！！", 10),

    # ── AI 处理中（ai_handling）────
    make_conv("conv-010", "user-010", "孙磊", "运维部", "SRE", "P6",
              "ai_handling", False, False, False,
              2, {},
              None, 0, False, "neutral",
              "Prometheus 告警：磁盘使用率超过 85%，怎么清理？", 90),

    make_conv("conv-011", "user-011", "马超", "研发部", "实习生", "P3",
              "ai_handling", False, False, False,
              1, {},
              None, 0, False, "neutral",
              "Git 提交时提示 'fatal: unable to access'，怎么解决？", 150),

    # ── 已结单（resolved）────
    make_conv("conv-012", "user-001", "张伟", "财务部", "经理", "P6",
              "resolved", False, False, False,
              3, {},
              "agent-001", 0, False, "neutral",
              "谢谢，VPN 问题已解决，是密码过期了", 300),

    make_conv("conv-013", "user-007", "周婷", "行政部", "行政主管", "P5",
              "resolved", False, False, False,
              2, {},
              "agent-001", 0, False, "neutral",
              "IT 已来处理，投影仪换了新的HDMI线，正常了", 500),

    make_conv("conv-014", "user-012", "杨阳", "公关部", "专员", "P4",
              "resolved", False, False, False,
              1, {},
              "agent-001", 0, False, "neutral",
              "耳机没声音的问题解决了，是静音键被误触了😅", 800),

    make_conv("conv-015", "user-005", "刘芳", "人事部", "HRBP", "P6",
              "resolved", False, False, False,
              2, {},
              "agent-001", 0, False, "neutral",
              "OA 白屏问题已恢复，是浏览器缓存导致的，清掉就好了", 1200),
]

# 插入数据库（INSERT OR IGNORE 避免主键冲突，重复运行安全）
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()

cur.execute("SELECT COUNT(*) FROM conversations")
before = cur.fetchone()[0]
print(f"插入前已有 {before} 条记录")

sql = """
INSERT OR IGNORE INTO conversations (
    id, corp_id, employee_id, employee_name, department, position, level,
    status, is_vip, is_pinned, is_todo, urgency_score, tags,
    assigned_agent_id, collaborating_agent_ids, ai_substantive_reply_count,
    impact_scope, is_blocking, emotion_state, dify_conversation_id,
    last_message_at, last_message_summary, created_at, updated_at
) VALUES (
    ?,?,?,?,?,?,?,
    ?,?,?,?,?,?,
    ?,?,?,
    ?,?,?,?,
    ?,?,?,?
)
"""

cur.executemany(sql, rows)
conn.commit()

cur.execute("SELECT COUNT(*) FROM conversations")
after = cur.fetchone()[0]
print(f"✅ 插入后共 {after} 条记录（新增 {after - before} 条会话 Mock 数据）！")
conn.close()
