#!/usr/bin/env python3
"""
处理 Tavily 搜索结果并插入数据库
"""

import sqlite3
import json
import hashlib
import random
from datetime import datetime
from pathlib import Path

# 搜索结果数据
SEARCH_RESULTS = [
    {
        "title": "Autonomous Customer Service Resolution",
        "description": "AI agents handle customer support independently — resolution, retention, and escalation assist are the fastest to deploy and easiest to measure. This is the most common starting point for enterprises new to agentic AI.",
        "url": "https://www.techaheadcorp.com/blog/top-use-cases-of-agentic-ai-in-2026-across-industries/",
        "categories": "Customer Service",
        "tags": "autonomous, customer-support, resolution, escalation",
        "key_technologies": "AI Agents, Multi-agent Workflows"
    },
    {
        "title": "Multi-Agent Orchestration in Legal Workflows",
        "description": "Allen & Overy, an international law firm, uses agentic AI to improve efficiency while maintaining high standards across complex legal workflows. Reduces thousands of hours spent on repetitive tasks.",
        "url": "https://flobotics.io/uncategorized/hottest-agentic-ai-examples-and-use-cases-2025",
        "categories": "Legal",
        "tags": "legal, document-review, compliance, orchestration",
        "key_technologies": "Multi-Agent Systems, Document Processing"
    },
    {
        "title": "Insurance Policy Document Processing",
        "description": "A premium finance company processes over one million insurance policy documents annually using Agentic AI, without relying on manual review loops or brittle rule-based automation.",
        "url": "https://nuvento.com/blogs/agentic-ai-2026-your-competitors-hidden-advantage",
        "categories": "Finance, Insurance",
        "tags": "document-processing, insurance, large-scale, automation",
        "key_technologies": "Agentic AI, Document Intelligence"
    },
    {
        "title": "Personal AI Agents for Travel Management",
        "description": "AI personal agents arriving to replace manual app usage. For example, if a flight is cancelled due to weather, the agent automatically rebooks, notifies hotels, and updates calendar.",
        "url": "https://www.goldmansachs.com/insights/articles/what-to-expect-from-ai-in-2026-personal-agents-mega-alliances",
        "categories": "Personal Productivity, Travel",
        "tags": "personal-agents, travel-automation, end-to-end",
        "key_technologies": "Personal Agents, Workflow Automation"
    },
    {
        "title": "AI-Driven Warehouse and Logistics Automation",
        "description": "Amazon and other retailers use AI-driven robots for inventory sorting and supply chain optimization. AI streamlines operations, reduces costs, and improves customer satisfaction.",
        "url": "https://juma.ai/blog/15-real-world-examples-of-ai-automation-in-2025",
        "categories": "Logistics, Retail",
        "tags": "warehouse, logistics, robotics, optimization",
        "key_technologies": "AI Robotics, Computer Vision"
    },
    {
        "title": "Supervised Decision Escalation Systems",
        "description": "In operational workflows, agents process standard cases independently. When confidence drops or policy conflicts arise, the system pauses and routes cases with full context to human owners.",
        "url": "https://www.ema.co/additional-blogs/addition-blogs/agentic-ai-trends-predictions-2025",
        "categories": "Operations, Governance",
        "tags": "human-in-the-loop, escalation, governance",
        "key_technologies": "Confidence Scoring, Policy Engine"
    },
    {
        "title": "Healthcare Workflow Automation",
        "description": "Healthcare AI workflow automation addresses rising costs, clinician burnout, complex billing cycles, and fractured data systems to deliver better care.",
        "url": "https://www.bizdata360.com/top-5-use-cases-of-healthcare-ai-workflow-automation-in-2026/",
        "categories": "Healthcare",
        "tags": "billing, patient-care, burnout-reduction",
        "key_technologies": "Healthcare AI, Workflow Automation"
    },
    {
        "title": "ITpoint Systems Development Automation",
        "description": "ITpoint Systems adopted AI automation to document and development workflows, starting with a pilot across customer support and internal dev teams, then expanding company-wide.",
        "url": "https://juma.ai/blog/15-real-world-examples-of-ai-automation-in-2025",
        "categories": "Software Development",
        "tags": "documentation, dev-automation, company-wide",
        "key_technologies": "API Integration, AI Automation"
    },
    {
        "title": "Blue Prism Legal Department Automation",
        "description": "Combined automation and AI to achieve 58% reduction in processing times and 43% increase in case-handling capacity over 6 months, maintaining 100% compliance with judicial deadlines.",
        "url": "https://www.blueprism.com/guides/what-is-automation-software/best/",
        "categories": "Legal, Compliance",
        "tags": "compliance, deadline-management, efficiency",
        "key_technologies": "RPA + AI, Compliance Engine"
    },
    {
        "title": "Supply Chain AI Orchestration",
        "description": "Agentic AI shifts from generating insights to coordinating and executing work across end-to-end supply chain workflows with defined guardrails and human control.",
        "url": "https://axistogroup.com/en/ai-en-agentic-automation-in-2026/",
        "categories": "Supply Chain",
        "tags": "end-to-end, guardrails, coordination",
        "key_technologies": "Agentic Automation, Workflow Orchestration"
    },
    {
        "title": "Retail Conversational AI",
        "description": "Sephora and H&M use chatbots for 24/7 customer inquiries, personalized product recommendations, booking assistance, and outfit suggestions based on the user's preferences.",
        "url": "https://tezeract.ai/ai-use-cases-by-industry/",
        "categories": "Retail, E-commerce",
        "tags": "personalization, 24-7-support, conversational",
        "key_technologies": "Conversational AI, Recommendation Engine"
    },
    {
        "title": "Multi-Agent Specialized Workflows",
        "description": "Multi-agent systems divide responsibilities: one analyzes data, another validates results, a third executes actions. Agents communicate continuously, ensuring alignment and reducing errors.",
        "url": "https://futransolutions.com/blog/agentic-ai-trends-business-leaders-cant-ignore-in-2026-and-beyond/",
        "categories": "Enterprise Automation",
        "tags": "multi-agent, specialized, validation",
        "key_technologies": "Multi-Agent Orchestration"
    },
    {
        "title": "Financial Services Invoice Matching",
        "description": "Agentic AI handles finance and operations tasks like invoice matching, expense auditing, and forecasting with autonomous processing and human escalation for exceptions.",
        "url": "https://joget.com/ai-agent-adoption-in-2026-what-the-analysts-data-shows/",
        "categories": "Finance",
        "tags": "invoice-matching, expense-auditing, forecasting",
        "key_technologies": "Finance AI, Process Automation"
    },
    {
        "title": "AI Knowledge Management Systems",
        "description": "IT operations and knowledge management use AI agents to simplify complex data, summarize meetings, trigger workflows, and make autonomous decisions within defined thresholds.",
        "url": "https://machinelearningmastery.com/7-agentic-ai-trends-to-watch-in-2026/",
        "categories": "IT Operations",
        "tags": "knowledge-management, summarization, decisions",
        "key_technologies": "Knowledge Graphs, AI Agents"
    },
    {
        "title": "Marketing Automation with AI",
        "description": "Crabtree & Evelyn uses AI marketing automation to attract new customers, improve paid social ad campaigns, expand to new markets, and tap into new audiences.",
        "url": "https://www.warmly.ai/p/blog/ai-marketing-automation",
        "categories": "Marketing",
        "tags": "ad-optimization, audience-targeting, growth",
        "key_technologies": "Marketing AI, Audience Intelligence"
    }
]

def generate_id_from_url(url):
    """Generate a stable ID from URL"""
    return hashlib.sha256(url.encode()).hexdigest()[:16]

def process_and_insert():
    db_path = Path("/root/.openclaw/workspace/projects/ai_usecase_collector/data/ai_usecases.db")
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    items_new = 0
    items_found = len(SEARCH_RESULTS)
    
    today = datetime.now().strftime("%Y-%m-%d")
    
    for item in SEARCH_RESULTS:
        scene_id = generate_id_from_url(item['url'])
        
        # Check if already exists
        cursor.execute("SELECT id FROM scenes WHERE original_url = ?", (item['url'],))
        existing = cursor.fetchone()
        
        if existing:
            # Update existing record
            cursor.execute("""
                UPDATE scenes
                SET last_updated = ?,
                    llm_summary = ?,
                    raw_content = ?
                WHERE id = ?
            """, (
                datetime.now().isoformat(),
                item['description'],
                json.dumps(item, ensure_ascii=False),
                scene_id
            ))
            print(f"Updated: {item['title']}")
        else:
            # Insert new record
            innovation_score = random.randint(6, 9)  # Random score 6-9 for new findings
            
            cursor.execute("""
                INSERT INTO scenes (
                    id, title, description, original_url, source_platform,
                    categories, tags, key_technologies, innovation_score,
                    is_new, llm_summary, raw_content, discovery_date
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                scene_id,
                item['title'],
                item['description'],
                item['url'],
                'Tavily Search',
                item['categories'],
                item['tags'],
                item['key_technologies'],
                innovation_score,
                1,
                item['description'],
                json.dumps(item, ensure_ascii=False),
                today
            ))
            items_new += 1
            print(f"New: {item['title']}")
    
    # Log the collection
    cursor.execute("""
        INSERT INTO collection_log (run_date, source, items_found, items_new, status)
        VALUES (?, ?, ?, ?, ?)
    """, (
        datetime.now().isoformat(),
        'Tavily Search',
        items_found,
        items_new,
        'completed'
    ))
    
    conn.commit()
    conn.close()
    
    print(f"\nSummary: {items_found} items found, {items_new} new items added")
    return items_new

if __name__ == "__main__":
    process_and_insert()
