#!/usr/bin/env python3
"""临时脚本：从今日搜索结果插入新场景"""

import sqlite3
import json
import uuid
from datetime import datetime

# 新发现的场景数据
new_scenes = [
    {
        "title": "Autonomous Customer Service Resolution",
        "description": "AI agents handle end-to-end customer service including ticket resolution, refunds, escalations, and omnichannel support. Saves teams 40+ hours monthly.",
        "categories": "Customer Service,Support",
        "tags": "autonomous,ticket-resolution,refunds,omnichannel",
        "key_technologies": "Agentic AI,Multi-Agent Systems",
        "innovation_score": 85,
        "source_platform": "Web Search",
        "impact": "Saves teams 40+ hours monthly"
    },
    {
        "title": "Invoice Matching and Reconciliation",
        "description": "AI automates invoice matching, reconciliation, and expense auditing in finance operations. Accelerates processes by 30–50%.",
        "categories": "Finance,Operations",
        "tags": "finance,automation,reconciliation,auditing",
        "key_technologies": "AI Agents,RPA Integration",
        "innovation_score": 80,
        "source_platform": "Web Search",
        "impact": "Accelerates processes by 30–50%"
    },
    {
        "title": "Multi-Agent Security Compliance",
        "description": "Agents collaborate for anomaly/threat detection, policy enforcement, and incident remediation with proactive risk reduction.",
        "categories": "Security,Compliance,IT",
        "tags": "security,threat-detection,compliance,incident-response",
        "key_technologies": "Multi-Agent Systems,Security AI",
        "innovation_score": 90,
        "source_platform": "Web Search",
        "impact": "Enables proactive risk reduction"
    },
    {
        "title": "Agentic Lead Generation and Qualification",
        "description": "AI agents scrape LinkedIn/Google Maps for prospects, enrich leads with contact info, and generate personalized outreach emails.",
        "categories": "Sales,Marketing",
        "tags": "lead-generation,prospecting,outreach,automation",
        "key_technologies": "Web Scraping Agents,Email Generation",
        "innovation_score": 88,
        "source_platform": "Web Search",
        "impact": "2–3x pipeline velocity improvement"
    },
    {
        "title": "Predictive Maintenance and Supply Chain Optimization",
        "description": "AI analyzes sensor data and historical records to predict equipment failures, schedule maintenance, and optimize inventory/logistics.",
        "categories": "Manufacturing,Supply Chain",
        "tags": "predictive-maintenance,supply-chain,optimization",
        "key_technologies": "IoT Analytics,Predictive AI",
        "innovation_score": 87,
        "source_platform": "Web Search",
        "impact": "Minimizes downtime in manufacturing"
    },
    {
        "title": "End-to-End Business Process Automation",
        "description": "Automates full workflows like customer onboarding, document verification, approvals, and closure by merging RPA with AI for decisions.",
        "categories": "Business Process,Operations",
        "tags": "onboarding,workflow-automation,RPA,AI",
        "key_technologies": "RPA,AI Decision Engines",
        "innovation_score": 85,
        "source_platform": "Web Search",
        "impact": "Reduces hand-offs and scales high-volume tasks"
    },
    {
        "title": "Customer 360 Data Integration",
        "description": "Unifies fragmented data from CRM, marketing, and support platforms; detects duplicates and enriches profiles for real-time insights.",
        "categories": "Data Integration,Customer Experience",
        "tags": "data-unification,Customer-360,CRM,real-time",
        "key_technologies": "Data Integration,Real-time Analytics",
        "innovation_score": 82,
        "source_platform": "Web Search",
        "impact": "Enables personalized experiences and better sales targeting"
    },
    {
        "title": "Competitive Intelligence and SEO Automation",
        "description": "Analyzes rivals' content activity, ads, or keywords; generates reports on patterns and evaluates AI visibility for strategic positioning.",
        "categories": "Marketing,Competitive Intelligence",
        "tags": "competitive-intelligence,SEO,analytics",
        "key_technologies": "Web Analytics,SEO Tools",
        "innovation_score": 80,
        "source_platform": "Web Search",
        "impact": "Strategic positioning and visibility insights"
    },
    {
        "title": "Meeting Preparation and Knowledge Management",
        "description": "Agents research upcoming meetings across CRM, email, Slack, and web sources; or extract insights from articles/tickets into structured sheets.",
        "categories": "Productivity,Knowledge Management",
        "tags": "meeting-prep,research,knowledge-management",
        "key_technologies": "Multi-Source Research,Knowledge Graph",
        "innovation_score": 84,
        "source_platform": "Web Search",
        "impact": "Streamlines meeting preparation and knowledge extraction"
    },
    {
        "title": "Automated Compliance, Audit, and Marketing Harmonization",
        "description": "Automates audit trails, report generation, data cleansing from multiple platforms, and real-time campaign optimization.",
        "categories": "Compliance,Audit,Marketing",
        "tags": "compliance,audit,marketing-optimization",
        "key_technologies": "Audit AI,Marketing Analytics",
        "innovation_score": 83,
        "source_platform": "Web Search",
        "impact": "Cuts review time by 70% and reduces regulatory risks"
    }
]

# 数据库路径
db_path = "/root/.openclaw/workspace/projects/ai_usecase_collector/data/ai_usecases.db"

# 连接数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

# 插入新场景
inserted_count = 0
skipped_count = 0

for scene in new_scenes:
    scene_id = str(uuid.uuid4())
    current_time = datetime.now().isoformat()

    # 检查是否已存在相似标题
    cursor.execute("SELECT id FROM scenes WHERE title = ?", (scene["title"],))
    existing = cursor.fetchone()

    if existing:
        skipped_count += 1
        print(f"跳过已存在: {scene['title']}")
        continue

    # 插入新场景
    cursor.execute("""
        INSERT INTO scenes (
            id, title, description, source_platform,
            discovery_date, categories, tags,
            key_technologies, innovation_score,
            is_new, llm_summary, last_updated
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        scene_id,
        scene["title"],
        scene["description"],
        scene["source_platform"],
        current_time,
        scene["categories"],
        scene["tags"],
        scene["key_technologies"],
        scene["innovation_score"],
        1,  # is_new
        json.dumps({"impact": scene.get("impact", "")}),
        current_time
    ))

    inserted_count += 1
    print(f"插入新场景: {scene['title']}")

# 记录日志
cursor.execute("""
    INSERT INTO collection_log (run_date, source, items_found, items_new, status)
    VALUES (?, ?, ?, ?, ?)
""", (current_time, "Daily Web Search", len(new_scenes), inserted_count, "completed"))

conn.commit()
conn.close()

print(f"\n✅ 完成: 插入 {inserted_count} 个新场景，跳过 {skipped_count} 个已存在的场景")
