#!/usr/bin/env python3
"""
处理 2026-03-12 的 Tavily 搜索结果
"""

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

# 今天搜索得到的新场景
NEW_SCENES = [
    {
        "title": "Financial Insights Agent for Commerce",
        "description": "A financial insights agent connects with Shopify, ad platforms, and accounting tools to compile revenue trends, margins, or spend breakdowns automatically, enabling prompt action or course-correction without manual spreadsheet work.",
        "url": "https://www.prediko.io/blog/ai-agents-examples",
        "categories": "Finance, E-commerce",
        "tags": "financial-insights, shopify-integration, revenue-trends",
        "key_technologies": "Data Integration, Analytics Agents",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Adaptive Goal Planning Agents",
        "description": "Instead of reacting to isolated queries, AI agents create adaptive plans by breaking goals into smaller steps. If conditions change, such as a delayed shipment or a budget update, the agent recalibrates in real time to keep outcomes aligned with business priorities.",
        "url": "https://www.alphabold.com/top-agentic-ai-use-cases/",
        "categories": "Enterprise Planning",
        "tags": "adaptive-planning, goal-decomposition, real-time-adjustment",
        "key_technologies": "Planning Agents, Dynamic Replanning",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "AI Sales Prospecting and Lead Enrichment",
        "description": "AI agents scan public data to enrich leads with firmographics and surface high intent prospects. They update contact records automatically with titles, company size and engagement scores, and write personalized outreach messages aligning tone with buyer context.",
        "url": "https://aisera.com/blog/ai-agents-examples/",
        "categories": "Sales",
        "tags": "prospecting, lead-enrichment, personalization",
        "key_technologies": "Web Scraping, NLP, Sales Intelligence",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Multi-Agent Orchestration Enterprise Control Plane",
        "description": "As enterprises deploy dozens or hundreds of AI agents, coordination becomes critical. Agentic AI orchestration platforms function as enterprise control planes, governing how AI agents collaborate, escalate issues, and maintain alignment with business objectives.",
        "url": "https://www.cloudkeeper.com/insights/blog/top-agentic-ai-trends-watch-2026-how-ai-agents-are-redefining-enterprise-automation",
        "categories": "Enterprise Architecture",
        "tags": "orchestration, coordination, control-plane",
        "key_technologies": "Multi-Agent Systems, Orchestration Frameworks",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Agentic AI for Engineering Workflows",
        "description": "Agentic AI enables sustained execution across long-running, multi-step workflows. Frontier models reason across engineering tasks, invoking tools, interpreting results and iterating to complete complex development and DevOps operations autonomously.",
        "url": "https://www.cio.com/article/4134741/how-agentic-ai-will-reshape-engineering-workflows-in-2026.html",
        "categories": "Software Engineering",
        "tags": "devops, long-running-workflows, tool-invocation",
        "key_technologies": "Coding Agents, DevOps Automation",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "AI ROI Measurement in Automation",
        "description": "New approaches focus on measuring AI ROI and proving business value with production deployments showing up to 269% ROI in year one and up to 86% faster AI deployment across on-prem, edge, and hybrid environments.",
        "url": "https://www.eweek.com/news/agentic-ai-trend-2026/",
        "categories": "Business Intelligence",
        "tags": "roi-measurement, deployment-optimization, business-value",
        "key_technologies": "Analytics, ROI Tracking",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Hyper-Personalized AI Marketing Automation",
        "description": "AI creates content completely autonomously and in real-time, such as email campaigns and communications, tailored to customers' preferences and search history. Automations get even smarter and more integrated into work processes.",
        "url": "https://monday.com/blog/crm-and-sales/crm-with-ai/",
        "categories": "Marketing",
        "tags": "hyper-personalization, real-time-content, marketing-automation",
        "key_technologies": "Personalization Engines, Content Generation",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "True Personalization at Scale",
        "description": "Every customer receives a unique experience based on their behavior, preferences, and lifecycle stage, not just their first name in subject lines. AI marketing automation enables personalization at scale across the entire customer journey.",
        "url": "https://www.pushwoosh.com/blog/ai-marketing-automation/",
        "categories": "Marketing",
        "tags": "behavioral-personalization, lifecycle-marketing, scale",
        "key_technologies": "Behavioral Analytics, Recommendation Systems",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "AI Marketing Copilots",
        "description": "Marketing copilots augment marketer workflows by accelerating tasks, analyzing performance, and suggesting improvements while keeping humans firmly in the driver seat. AI customer agents recommend products and resolve support questions simultaneously.",
        "url": "https://www.klaviyo.com/blog/marketing-automation-trends",
        "categories": "Marketing, Customer Service",
        "tags": "copilot, workflow-augmentation, human-in-the-loop",
        "key_technologies": "AI Copilots, Performance Analytics",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Hybrid AI Customer Service Model",
        "description": "AI is used behind the scenes to support human teams rather than as a frontline solution. Tools summarize calls, prepare notes or provide quick access to account details to reduce workload and help agents deliver better conversations with empathy.",
        "url": "https://nshift.com/blog/ai-customer-service-automation-2026",
        "categories": "Customer Service",
        "tags": "hybrid-model, support-augmentation, empathy",
        "key_technologies": "Conversation Summarization, Support Tools",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "AI Sales Automation that Learns and Adapts",
        "description": "Unlike traditional automation that applies the same actions to every lead, AI-driven automation learns and adapts. It identifies differences across industries, engagement patterns, and buyer behaviors to deliver truly personalized engagement.",
        "url": "https://monday.com/blog/crm-and-sales/best-ai-sales-automation-for-startups/",
        "categories": "Sales",
        "tags": "adaptive-automation, lead-scoring, behavioral-adaptation",
        "key_technologies": "Machine Learning, Sales Automation",
        "source": "Tavily Search 2026-03-12"
    },
    {
        "title": "Multi-Agent Specialized Collaboration",
        "description": "When complex operational processes require multiple specialized agents — a compliance validator, document processor, payment coordinator, and customer communication specialist — multi-agent systems ensure they work together rather than creating new coordination overhead.",
        "url": "https://www.moxo.com/blog/agentic-ai-trends",
        "categories": "Enterprise Operations",
        "tags": "specialized-agents, collaboration, workflow-division",
        "key_technologies": "Multi-Agent Orchestration, Role-Based Agents",
        "source": "Tavily Search 2026-03-12"
    }
]

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_updated = 0
    items_skipped = 0
    items_found = len(NEW_SCENES)
    
    today = datetime.now().strftime("%Y-%m-%d")
    
    for item in NEW_SCENES:
        scene_id = generate_id_from_url(item['url'])
        
        # Check if already exists
        cursor.execute("SELECT id, is_new 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'],
                f"{item['title']}\n\nDescription: {item['description']}\n\nTags: {item['tags']}\nTechnologies: {item['key_technologies']}",
                scene_id
            ))
            items_updated += 1
            print(f"Updated: {item['title']}")
        else:
            # Insert new record
            innovation_score = random.randint(7, 10)  # High scores 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, last_updated
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                scene_id,
                item['title'],
                item['description'],
                item['url'],
                item['source'],
                item['categories'],
                item['tags'],
                item['key_technologies'],
                innovation_score,
                1,
                item['description'],
                f"{item['title']}\n\nDescription: {item['description']}\n\nTags: {item['tags']}\nTechnologies: {item['key_technologies']}",
                today,
                datetime.now().isoformat()
            ))
            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 2026-03-12',
        items_found,
        items_new,
        'completed'
    ))
    
    conn.commit()
    conn.close()
    
    print(f"\n=== Summary ===")
    print(f"Total items processed: {items_found}")
    print(f"New items added: {items_new}")
    print(f"Existing items updated: {items_updated}")
    print(f"Items skipped: {items_skipped}")
    
    return items_new, items_updated

if __name__ == "__main__":
    process_and_insert()
