#!/usr/bin/env python3
"""
简单的模板数据插入脚本
直接使用数据库连接，不依赖app模块
"""
import pymysql
import json
import uuid
from datetime import datetime, timedelta
import random

# 数据库配置（从config.py中获取）
DB_CONFIG = {
    'host': 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com',
    'port': 24936,
    'user': 'root',
    'password': '!Rjb12191',
    'database': 'agent_db',
    'charset': 'utf8mb4'
}

# 模板数据
TEMPLATES = [
    {
        "name": "智能客服工作流",
        "description": "一个完整的智能客服工作流，支持自动回复、问题分类和转人工功能。",
        "category": "llm",
        "tags": ["客服", "AI", "自动化"],
        "is_featured": True
    },
    {
        "name": "数据清洗工作流",
        "description": "自动清洗和转换数据，支持多种数据源格式。",
        "category": "data_processing",
        "tags": ["数据处理", "ETL", "数据清洗"],
        "is_featured": False
    },
    {
        "name": "定时数据同步",
        "description": "定时从数据库同步数据到另一个系统，支持增量同步。",
        "category": "automation",
        "tags": ["定时任务", "数据同步", "自动化"],
        "is_featured": True
    },
    {
        "name": "API数据聚合",
        "description": "从多个API获取数据并聚合处理，支持错误重试。",
        "category": "integration",
        "tags": ["API", "数据聚合", "集成"],
        "is_featured": False
    },
    {
        "name": "邮件通知工作流",
        "description": "根据条件发送邮件通知，支持HTML格式和附件。",
        "category": "automation",
        "tags": ["邮件", "通知", "自动化"],
        "is_featured": True
    },
    {
        "name": "内容生成工作流",
        "description": "使用AI生成文章、摘要等内容，支持多种格式输出。",
        "category": "llm",
        "tags": ["AI", "内容生成", "LLM"],
        "is_featured": False
    },
    {
        "name": "文件处理工作流",
        "description": "批量处理文件，支持上传、下载、格式转换等功能。",
        "category": "data_processing",
        "tags": ["文件处理", "批量操作"],
        "is_featured": False
    },
    {
        "name": "Webhook触发器",
        "description": "接收外部Webhook请求并触发工作流，支持多种认证方式。",
        "category": "integration",
        "tags": ["Webhook", "触发器", "集成"],
        "is_featured": True
    }
]

# 简单的节点和边配置
SIMPLE_NODES = [
    {"id": "start", "type": "start", "position": {"x": 100, "y": 100}, "data": {"label": "开始"}},
    {"id": "input", "type": "input", "position": {"x": 300, "y": 100}, "data": {"label": "输入"}},
    {"id": "process", "type": "transform", "position": {"x": 500, "y": 100}, "data": {"label": "处理"}},
    {"id": "output", "type": "output", "position": {"x": 700, "y": 100}, "data": {"label": "输出"}},
    {"id": "end", "type": "end", "position": {"x": 900, "y": 100}, "data": {"label": "结束"}}
]

SIMPLE_EDGES = [
    {"id": "e1", "source": "start", "target": "input"},
    {"id": "e2", "source": "input", "target": "process"},
    {"id": "e3", "source": "process", "target": "output"},
    {"id": "e4", "source": "output", "target": "end"}
]

def insert_templates():
    """插入模板数据"""
    try:
        # 连接数据库
        connection = pymysql.connect(**DB_CONFIG)
        
        try:
            with connection.cursor() as cursor:
                # 获取第一个用户ID
                cursor.execute("SELECT id FROM users LIMIT 1")
                user_result = cursor.fetchone()
                
                if not user_result:
                    print("❌ 没有找到用户，请先创建用户")
                    return
                
                user_id = user_result[0]
                print(f"✅ 使用用户ID: {user_id}")
                print()
                
                # 检查模板是否已存在
                cursor.execute("SELECT COUNT(*) FROM workflow_templates WHERE user_id = %s", (user_id,))
                existing_count = cursor.fetchone()[0]
                
                if existing_count > 0:
                    print(f"ℹ️  已存在 {existing_count} 个模板，跳过插入")
                    return
                
                # 插入模板
                added_count = 0
                for template_info in TEMPLATES:
                    template_id = str(uuid.uuid4())
                    nodes_json = json.dumps(SIMPLE_NODES, ensure_ascii=False)
                    edges_json = json.dumps(SIMPLE_EDGES, ensure_ascii=False)
                    tags_json = json.dumps(template_info["tags"], ensure_ascii=False)
                    
                    view_count = random.randint(0, 1000)
                    use_count = random.randint(0, 100)
                    rating_count = random.randint(0, 50)
                    rating_avg = round(random.uniform(3.5, 5.0), 1)
                    days_ago = random.randint(0, 30)
                    created_at = datetime.now() - timedelta(days=days_ago)
                    updated_at = datetime.now() - timedelta(days=random.randint(0, 7))
                    
                    sql = """
                    INSERT INTO workflow_templates (
                        id, name, description, category, tags, nodes, edges,
                        is_public, is_featured, view_count, use_count, rating_count, rating_avg,
                        user_id, created_at, updated_at
                    ) VALUES (
                        %s, %s, %s, %s, %s, %s, %s,
                        %s, %s, %s, %s, %s, %s,
                        %s, %s, %s
                    )
                    """
                    
                    cursor.execute(sql, (
                        template_id,
                        template_info["name"],
                        template_info["description"],
                        template_info["category"],
                        tags_json,
                        nodes_json,
                        edges_json,
                        True,
                        template_info["is_featured"],
                        view_count,
                        use_count,
                        rating_count,
                        rating_avg,
                        user_id,
                        created_at,
                        updated_at
                    ))
                    added_count += 1
                    print(f"✅ 添加模板: {template_info['name']}")
                
                connection.commit()
                
                print()
                print("=" * 60)
                print(f"✅ 数据添加完成！")
                print(f"   新增: {added_count} 个模板")
                print("=" * 60)
                
                # 查询总数
                cursor.execute("SELECT COUNT(*) FROM workflow_templates WHERE user_id = %s", (user_id,))
                total_count = cursor.fetchone()[0]
                print(f"   当前模板总数: {total_count} 个")
                
        finally:
            connection.close()
            
    except Exception as e:
        print(f"❌ 执行失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    print("=" * 60)
    print("模板市场假数据生成工具")
    print("=" * 60)
    print()
    insert_templates()
