#!/usr/bin/env python3
"""Store collected AI use case scenes into SQLite."""
import sqlite3, json, uuid, os

DB_PATH = os.path.join(os.path.dirname(__file__), '..', 'data', 'ai_usecases.db')

SCENES = [
    {
        "title": "ESP32 自动买菜 Agent (zclaw)",
        "description": "用 ESP32 硬件 + 浏览器工具自动生成购物清单、构建购物车、验证订单，仅最终确认需人工介入。轻量级个人 Agent 的极致体现。",
        "original_url": "https://news.ycombinator.com/item?id=47100232",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Personal Automation", "IoT + AI"]),
        "tags": json.dumps(["ESP32", "browser-tool", "grocery", "hardware-agent", "lightweight"]),
        "key_technologies": json.dumps(["ESP32", "browser automation", "LLM"]),
        "innovation_score": 9
    },
    {
        "title": "Agent Swarm：自我学习的多 Agent 团队",
        "description": "开源多 Agent 系统，具备个人/共享记忆(SQLite)，lead agent 每日评估工作、传播改进、通过 Docker 部署运行流程优化任务。Agent 团队能随时间积累经验并自我进化。",
        "original_url": "https://news.ycombinator.com/item?id=47165046",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Multi-Agent Systems", "Self-Improving AI"]),
        "tags": json.dumps(["multi-agent", "self-learning", "SQLite-memory", "Docker", "open-source"]),
        "key_technologies": json.dumps(["Docker", "SQLite", "multi-agent framework"]),
        "innovation_score": 8
    },
    {
        "title": "AI Agent 权限治理系统",
        "description": "AI Agent 实现权限系统和自动发现，记录错误、在操作前检查审批(如付款)，通过权限评分追踪过度授权。解决多步骤工作流中的复合错误问题。",
        "original_url": "https://news.ycombinator.com/item?id=47157574",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Governance & Safety", "Enterprise AI"]),
        "tags": json.dumps(["permissions", "governance", "safety", "multi-step", "trust"]),
        "key_technologies": json.dumps(["permission scoring", "auto-discovery", "approval workflows"]),
        "innovation_score": 8
    },
    {
        "title": "渐进式自主权：游戏工作室的 Agent 信任机制",
        "description": "Agent 从草稿模式(需审批)开始，基于编辑距离反馈、时间衰减信任分、最弱环节链逐步获得自主权。应用于邮件、项目创建、排程等任务。",
        "original_url": "https://news.ycombinator.com/item?id=47143741",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Earned Autonomy", "Enterprise AI"]),
        "tags": json.dumps(["trust-score", "earned-autonomy", "game-studio", "progressive-delegation"]),
        "key_technologies": json.dumps(["edit distance feedback", "time-decay trust", "weakest-link chains"]),
        "innovation_score": 9
    },
    {
        "title": "TeamOut：AI Agent 编排公司团建",
        "description": "AI Agent 编排场地搜索(向量嵌入)、成本估算、预算对比、报价获取、团队沟通。跨对话保持状态上下文，处理不断变化的约束而不捏造数据。",
        "original_url": "https://news.ycombinator.com/item?id=47151598",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Event Planning", "Agentic Workflow"]),
        "tags": json.dumps(["event-planning", "vector-embeddings", "stateful", "multi-step"]),
        "key_technologies": json.dumps(["vector embeddings", "stateful conversations", "budget optimization"]),
        "innovation_score": 7
    },
    {
        "title": "Personal CFO Agent：AI 个人财务总监",
        "description": "监控银行API(Plaid)，预测现金流缺口，自动协商账单(通过邮件Agent脚本联系供应商)，微量投资ETF。用户报告年节省10-20%。",
        "original_url": "https://reddit.com/r/personalfinance/ai_agent_cfo_2025",
        "source_platform": "Reddit",
        "categories": json.dumps(["Personal Finance", "Personal Automation"]),
        "tags": json.dumps(["finance", "bank-API", "auto-negotiate", "investment", "Plaid"]),
        "key_technologies": json.dumps(["Plaid API", "Monte Carlo simulation", "SMTP email agent", "Robinhood API"]),
        "innovation_score": 9
    },
    {
        "title": "AI 心理健康日记分析师",
        "description": "Agent 读取每日语音笔记(Whisper转录)，检测情绪模式，建议微习惯，趋势恶化时自动预约治疗师(Calendly集成)。有用户用Ollama本地运行保护隐私。",
        "original_url": "https://reddit.com/r/automate/mental_health_journal_agent",
        "source_platform": "Reddit",
        "categories": json.dumps(["Health & Wellness", "Personal Automation"]),
        "tags": json.dumps(["mental-health", "whisper", "sentiment-analysis", "local-LLM", "privacy"]),
        "key_technologies": json.dumps(["Whisper", "sentiment analysis", "Ollama", "Calendly API"]),
        "innovation_score": 8
    },
    {
        "title": "自适应膳食规划 + 自动采购 Agent",
        "description": "Agent 群通过手机摄像头扫描冰箱(视觉模型)，交叉参考健身追踪器数据、过敏信息和预算，生成食谱、创建购物清单并通过Instacart API自动下单。用户报告节省30%杂货开支。",
        "original_url": "https://reddit.com/r/automate/adaptive_meal_planner",
        "source_platform": "Reddit",
        "categories": json.dumps(["Health & Wellness", "IoT + AI", "Personal Automation"]),
        "tags": json.dumps(["vision-model", "fitness-tracker", "grocery", "multi-agent", "cost-saving"]),
        "key_technologies": json.dumps(["GPT-4o vision", "Fitbit/Apple Health API", "USDA API", "Instacart API"]),
        "innovation_score": 9
    },
    {
        "title": "Stripe Minions：一次性端到端编码 Agent",
        "description": "Stripe 内部工具，Agent 能一次性完成端到端编码任务(如提交PR)，无需人工逐步引导。",
        "original_url": "https://news.ycombinator.com/item?id=47110495",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Software Development", "Enterprise AI"]),
        "tags": json.dumps(["Stripe", "one-shot-coding", "PR-automation", "enterprise"]),
        "key_technologies": json.dumps(["end-to-end coding agent", "Git/PR integration"]),
        "innovation_score": 8
    },
    {
        "title": "华为 iMaster 自愈网络",
        "description": "华为的自组织网络(SON)系统自主修复90%的故障，维修时间缩短60%。网络拥堵时Nokia系统无需命令即可自动重新路由流量。",
        "original_url": "https://bronson.ai/resources/ai-agent-use-cases/",
        "source_platform": "Web",
        "categories": json.dumps(["Telecom & Networks", "Self-Healing Systems"]),
        "tags": json.dumps(["Huawei", "self-healing", "SON", "telecom", "autonomous-repair"]),
        "key_technologies": json.dumps(["Self-Organizing Networks", "autonomous fault repair"]),
        "innovation_score": 7
    },
    {
        "title": "Kenco AMR：仓库拣货效率提升 300%",
        "description": "Kenco的自主移动机器人(AMR)将仓库拣货率从30-40单位/小时提升至120-150，吞吐量提高55%。AI驱动的物流自动化实例。",
        "original_url": "https://bronson.ai/resources/ai-agent-use-cases/#kenco",
        "source_platform": "Web",
        "categories": json.dumps(["Logistics & Warehousing", "Physical Automation"]),
        "tags": json.dumps(["AMR", "warehouse", "pick-rate", "logistics", "robotics"]),
        "key_technologies": json.dumps(["Autonomous Mobile Robots", "ML path planning"]),
        "innovation_score": 7
    },
    {
        "title": "AI 植物管家：IoT + Agent 自动养护",
        "description": "通过IoT传感器监测土壤湿度，自动浇水施肥，拍照识别病虫害并研究解决方案。智能家居 Agent 的有趣延伸。",
        "original_url": "https://reddit.com/r/homeautomation/ai_plant_butler",
        "source_platform": "Reddit",
        "categories": json.dumps(["Smart Home", "IoT + AI"]),
        "tags": json.dumps(["IoT", "plant-care", "sensors", "vision-model", "home-automation"]),
        "key_technologies": json.dumps(["IoT sensors", "computer vision", "Roomba-style API"]),
        "innovation_score": 7
    },
    {
        "title": "Email Zero Inbox：多 Agent 邮件管理系统",
        "description": "分类器Agent分拣邮件、摘要Agent压缩线程、回复Agent以你的风格起草回复(基于历史邮件微调)、归档Agent删除垃圾。还有'代笔模式'自动从RSS/arXiv研究主题并以你的语气撰写newsletter。Reddit爆款20k赞。",
        "original_url": "https://reddit.com/r/productivity/email_zero_inbox_agent",
        "source_platform": "Reddit",
        "categories": json.dumps(["Productivity", "Personal Automation", "Multi-Agent Systems"]),
        "tags": json.dumps(["email", "multi-agent", "fine-tuned", "newsletter", "ghostwriter"]),
        "key_technologies": json.dumps(["email classification", "style fine-tuning", "RSS/arXiv integration"]),
        "innovation_score": 8
    },
    {
        "title": "Agentplace：实时编辑的内部自动化 Agent 构建器",
        "description": "团队用Agentplace创建自定义Agent处理后端、数据库和集成，支持工作中实时编辑。Agent通过使用进化，废弃不用的自动化，支持客户端需求收集。",
        "original_url": "https://news.ycombinator.com/item?id=47174672",
        "source_platform": "HackerNews",
        "categories": json.dumps(["Internal Automation", "No-Code/Low-Code"]),
        "tags": json.dumps(["agent-builder", "real-time-editing", "evolving-agents", "team-workflow"]),
        "key_technologies": json.dumps(["custom agent builder", "real-time collaboration", "database integration"]),
        "innovation_score": 7
    }
]

def store():
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    inserted = 0
    skipped = 0
    for s in SCENES:
        sid = str(uuid.uuid4())[:8]
        try:
            c.execute('''INSERT INTO scenes (id, title, description, original_url, source_platform, categories, tags, key_technologies, innovation_score)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''',
                (sid, s['title'], s['description'], s['original_url'], s['source_platform'],
                 s['categories'], s['tags'], s.get('key_technologies',''), s.get('innovation_score', 0)))
            inserted += 1
        except sqlite3.IntegrityError:
            skipped += 1
    conn.commit()
    
    # Log this collection run
    c.execute('INSERT INTO collection_log (source, items_found, items_new, status) VALUES (?, ?, ?, ?)',
              ('web_search_batch_1', len(SCENES), inserted, 'success'))
    conn.commit()
    conn.close()
    print(f"✅ 入库完成: {inserted} 条新场景, {skipped} 条跳过(已存在)")

if __name__ == '__main__':
    store()
