#!/usr/bin/env python3
"""
AI 使用场景每日收集任务
"""
import sqlite3
import json
import hashlib
from datetime import datetime, timedelta
from pathlib import Path

# 数据库路径
DB_PATH = Path("/root/.openclaw/workspace/projects/ai_usecase_collector/data/ai_usecases.db")

# 搜索结果（从 Tavily 获取）
SEARCH_RESULTS = [
    {
        "title": "Beyond the Agentic AI Hype: How Leading Enterprises Make It Actually Work",
        "url": "https://techcrunch.com/sponsor/shelf/beyond-the-agentic-ai-hype-how-leading-enterprises-make-it-actually-work/",
        "description": "In 2026, leading organizations are using AI agents to transform customer experiences, streamline operations, and execute work in new ways, driving real business impact. AI agents are applied across front-end customer experiences and back-office operations.",
        "source": "TechCrunch",
        "categories": "Enterprise, Customer Experience",
        "tags": "Agentic AI, Enterprise AI, Automation",
        "key_technologies": "AI Agents, LLM"
    },
    {
        "title": "Nvidia shows future of self-driving cars, robots, AI agents",
        "url": "https://thenightly.com.au/business/nvidias-result-foreshadows-a-future-of-self-driving-cars-robots-and-personal-ai-agents--c-21762456",
        "description": "Personal AI agents that can list investment properties with right dimensions, arrange inspections, search for cheapest mortgages, and remind about upcoming birthdays.",
        "source": "The Nightly",
        "categories": "Personal Assistant, Real Estate",
        "tags": "Personal AI, Nvidia, Autonomous",
        "key_technologies": "AI Agents, Robotics"
    },
    {
        "title": "7 Ways AI Will Transform US Manufacturing by 2030",
        "url": "https://www.industryweek.com/sponsored/article/55358765-7-ways-ai-will-transform-us-manufacturing-by-2030",
        "description": "Plant managers will become agentic orchestrators—managing fleets of purpose-built AI agents designed to deliver specific outcomes. Each agent handles predictive maintenance, quality inspection, supply chain disruptions, or production scheduling.",
        "source": "IndustryWeek",
        "categories": "Manufacturing, Automation",
        "tags": "Agentic Orchestration, Manufacturing AI",
        "key_technologies": "AI Agents, Digital Twins"
    },
    {
        "title": "Four Ways Operators Are Using AI to Increase Competitiveness",
        "url": "https://www.telecoms.com/ai/four-ways-operators-are-using-ai-to-increase-competitiveness",
        "description": "Use of MCP (Model Context Protocol) to Integrate Systems and AI Agents. As Agentic AI expands across operators, MCP is set to become a key enabler for integrating AI with external systems.",
        "source": "Telecoms.com",
        "categories": "Telecommunications",
        "tags": "MCP, Agentic AI, Integration",
        "key_technologies": "MCP, LLM, AI Agents"
    },
    {
        "title": "What Is Agentic Automation, and Why Does It Matter?",
        "url": "https://www.moveworks.com/us/en/resources/blog/what-does-agentic-automation-mean",
        "description": "Agentic automation combines LLMs that understand human text, large action models (LAM) that decide actions, and generative AI. It's used for customer service, HR operations, and IT support automation.",
        "source": "Moveworks",
        "categories": "Enterprise Automation",
        "tags": "Agentic Automation, LAM, LLM",
        "key_technologies": "LLM, LAM, AI Agents"
    },
    {
        "title": "Agentic AI: How It Works and 7 Real-World Use Cases",
        "url": "https://www.exabeam.com/explainers/ai-cyber-security/agentic-ai-how-it-works-and-7-real-world-use-cases/",
        "description": "Agentic AI vs AI Agents: AI agents follow predefined rules while agentic AI can reason, plan, and adapt. Real-world use cases include cybersecurity, fraud detection, and automated threat response.",
        "source": "Exabeam",
        "categories": "Cybersecurity",
        "tags": "Agentic AI, Cybersecurity, Threat Detection",
        "key_technologies": "AI Agents, Machine Learning"
    },
    {
        "title": "Building Autonomous Systems: A Guide to Agentic AI Workflows",
        "url": "https://www.digitalocean.com/community/conceptual-articles/build-autonomous-systems-agentic-ai",
        "description": "Agentic workflows perform interpretation and execute plans based on high-level objectives. Can recursively decompose tasks into subtasks. Agents work together, engage in negotiation, and transfer tasks.",
        "source": "DigitalOcean",
        "categories": "Workflow Automation",
        "tags": "Autonomous Systems, Multi-Agent",
        "key_technologies": "Multi-Agent Systems, LLM"
    },
    {
        "title": "The Complete Guide to Building Agentic AI Workflows That Scale",
        "url": "https://galileo.ai/blog/ai-agentic-workflows",
        "description": "Customer service enhancement: Agents learn from every interaction, trimming average handle times. HR operations automation: Time-off approvals, employee onboarding, and policy Q&A.",
        "source": "Galileo AI",
        "categories": "Customer Service, HR",
        "tags": "Scalable Workflows, Customer Experience",
        "key_technologies": "AI Agents, LLM"
    },
    {
        "title": "10 Agentic AI Examples and Use Cases",
        "url": "https://boomi.com/blog/10-agentic-ai-use-cases/",
        "description": "Integration and automation examples across various industries. AI agents handling data integration, business process automation, and event-driven workflows.",
        "source": "Boomi",
        "categories": "Integration, Business Process",
        "tags": "Integration, BPA, Event-Driven",
        "key_technologies": "AI Agents, Integration Platforms"
    },
    {
        "title": "Agentic AI, explained",
        "url": "https://mitsloan.mit.edu/ideas-made-to-matter/agentic-ai-explained",
        "description": "JPMorgan Chase is exploring AI agents to detect fraud, provide customized financial advice, and automate loan approvals and legal document processing.",
        "source": "MIT Sloan",
        "categories": "Financial Services",
        "tags": "Banking, Fraud Detection, Automation",
        "key_technologies": "AI Agents, LLM"
    },
    {
        "title": "Understanding AI Agentic Workflows",
        "url": "https://www.atlassian.com/blog/artificial-intelligence/ai-agentic-workflows",
        "description": "Traditional automation follows exact steps and breaks on surprises. Agentic AI workflows can handle unexpected situations, make decisions dynamically, and recover from errors.",
        "source": "Atlassian",
        "categories": "Workflow Design",
        "tags": "Adaptive Automation, Error Handling",
        "key_technologies": "AI Agents, Workflow Engines"
    },
    {
        "title": "Future-Proofing Manufacturing Operations With AI",
        "url": "https://www.forbes.com/sites/forbes-listmaker/2026/03/03/future-proofing-manufacturing-operations-with-ai/",
        "description": "Modern AI systems can analyze data, plan, prioritize, simulate scenarios, and continuously improve. AI agents take concrete operational roles in manufacturing.",
        "source": "Forbes",
        "categories": "Manufacturing",
        "tags": "AI Operations, Simulation",
        "key_technologies": "AI Agents, Digital Twins"
    },
    {
        "title": "AI Is The 21st Century Force Multiplier",
        "url": "https://www.forbes.com/sites/chuckbrooks/2026/02/27/ai-is-the-21st-century-force-multiplier/",
        "description": "Healthcare uses AI for precision diagnostics, medication discovery, and predictive medicine. Financial services use AI for fraud detection, risk modeling, and algorithmic trading.",
        "source": "Forbes",
        "categories": "Healthcare, Finance",
        "tags": "Force Multiplier, Diagnostics, Trading",
        "key_technologies": "AI, ML, LLM"
    }
]

def get_db_connection():
    """获取数据库连接"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def insert_scene(conn, scene):
    """插入场景到数据库"""
    # 使用 URL 生成唯一 ID
    scene_id = hashlib.md5(scene['url'].encode()).hexdigest()[:16]

    cursor = conn.cursor()

    # 检查是否已存在
    cursor.execute("SELECT id FROM scenes WHERE original_url = ?", (scene['url'],))
    existing = cursor.fetchone()

    if existing:
        print(f"✓ 已存在: {scene['title'][:50]}...")
        return False

    # 插入新记录
    cursor.execute("""
        INSERT INTO scenes (
            id, title, description, original_url, source_platform,
            categories, tags, key_technologies, innovation_score,
            is_new, discovery_date, last_updated
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, (
        scene_id,
        scene['title'],
        scene['description'],
        scene['url'],
        scene['source'],
        scene['categories'],
        scene['tags'],
        scene['key_technologies'],
        7,  # innovation_score
        1,  # is_new
        datetime.now().isoformat(),
        datetime.now().isoformat()
    ))

    conn.commit()
    print(f"+ 新增: {scene['title'][:50]}...")
    return True

def get_recent_scenes(conn, days=7):
    """获取最近 N 天的新场景"""
    cutoff = (datetime.now() - timedelta(days=days)).isoformat()
    cursor = conn.cursor()
    cursor.execute("""
        SELECT * FROM scenes
        WHERE discovery_date > ?
        ORDER BY discovery_date DESC
    """, (cutoff,))
    return cursor.fetchall()

def get_top_scenes_by_innovation(conn, limit=10):
    """获取创新分数最高的场景"""
    cursor = conn.cursor()
    cursor.execute("""
        SELECT * FROM scenes
        ORDER BY innovation_score DESC, discovery_date DESC
        LIMIT ?
    """, (limit,))
    return cursor.fetchall()

def get_category_stats(conn):
    """获取分类统计"""
    cursor = conn.cursor()
    cursor.execute("""
        SELECT categories, COUNT(*) as count
        FROM scenes
        GROUP BY categories
        ORDER BY count DESC
    """)
    return cursor.fetchall()

def main():
    """主函数"""
    print("=" * 60)
    print("AI 使用场景每日收集任务")
    print("=" * 60)

    conn = get_db_connection()

    # 插入搜索结果
    print("\n📥 收集新场景...")
    new_count = 0
    for scene in SEARCH_RESULTS:
        if insert_scene(conn, scene):
            new_count += 1

    print(f"\n✅ 新增 {new_count} 个场景")

    # 获取统计信息
    print("\n📊 数据库统计:")
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) as total FROM scenes")
    total = cursor.fetchone()['total']
    print(f"   总场景数: {total}")

    cursor.execute("SELECT COUNT(*) as new FROM scenes WHERE is_new = 1")
    new_total = cursor.fetchone()['new']
    print(f"   新场景数: {new_total}")

    conn.close()

    return {
        'new_count': new_count,
        'total_count': total
    }

if __name__ == "__main__":
    stats = main()
    print(f"\n📋 任务完成! 新增: {stats['new_count']}, 总计: {stats['total_count']}")
