#!/usr/bin/env python3
"""
Obsidian Vault Inbox Processor
Reads raw ideas from inbox/, expands them with AI, categorizes, and archives.
"""

import os
import json
import re
from datetime import datetime
from pathlib import Path

# Try to import Hermes tools for AI processing
try:
    import sys
    sys.path.insert(0, '/root/.hermes/venvs/hermes/lib/python3.11/site-packages')
    from openai import OpenAI
    HAS_OPENAI = True
except ImportError:
    HAS_OPENAI = False

VAULT_ROOT = Path(__file__).parent.parent
INBOX_DIR = VAULT_ROOT / "inbox"
PROCESSED_DIR = VAULT_ROOT / "processed"
CATEGORIES_DIR = VAULT_ROOT / "categories"

# Category keywords for auto-classification
CATEGORY_KEYWORDS = {
    "技术": ["代码", "编程", "api", "架构", "docker", "linux", "算法", "技术", "开发", "系统"],
    "健康": ["断食", "运动", "睡眠", "饮食", "健康", "体重", "卡路里", "蛋白质"],
    "产品": ["用户", "需求", "功能", "体验", "产品", "设计", "界面"],
    "学习": ["学习", "课程", "读书", "笔记", "知识", "概念"],
    "商业": ["商业", "市场", "客户", "收入", "盈利", "投资"],
    "生活": ["生活", "家庭", "朋友", "旅行", "购物", "日常"],
    "创意": ["想法", "创意", "灵感", "如果", "假设", "想象"]
}

def extract_title(content: str) -> str:
    """Extract or generate a title from content, skipping metadata."""
    lines = content.strip().split('\n')
    for line in lines:
        line = line.strip()
        # Skip empty, comments, HTML comments, markdown headers
        if not line:
            continue
        if line.startswith('<!--') or line.startswith('-->'):
            continue
        if line.startswith('#'):
            # Use header text (strip # prefix) as title
            header = line.lstrip('#').strip()
            if header and len(header) < 60:
                return header
            continue
        if line.startswith('source:') or line.startswith('captured:'):
            continue
        # First real content line
        if len(line) < 60:
            return line
        else:
            return line[:60] + "..."
    return "无标题"

def categorize_idea(content: str) -> str:
    """Categorize idea based on keywords."""
    content_lower = content.lower()
    
    # Count keyword matches
    scores = {}
    for category, keywords in CATEGORY_KEYWORDS.items():
        score = sum(1 for kw in keywords if kw in content_lower)
        if score > 0:
            scores[category] = score
    
    if not scores:
        return "未分类"
    
    # Return highest scoring category
    return max(scores, key=scores.get)

def format_frontmatter(title: str, category: str, tags: list) -> str:
    """Generate YAML frontmatter for Obsidian."""
    tags_str = "\n".join(f"  - {tag}" for tag in tags)
    return f"""---
title: {title}
category: {category}
date: {datetime.now().strftime("%Y-%m-%d")}
tags:
{tags_str}
---

"""

def process_inbox_file(filepath: Path) -> bool:
    """Process a single inbox file."""
    try:
        content = filepath.read_text(encoding='utf-8')
        
        # Extract title
        title = extract_title(content)
        
        # Categorize
        category = categorize_idea(content)
        
        # Generate tags
        tags = [category.lower(), "inbox-processed"]
        if len(content) < 100:
            tags.append("碎片")
        else:
            tags.append("想法")
        
        # Generate frontmatter
        frontmatter = format_frontmatter(title, category, tags)
        
        # Create processed content
        processed_content = frontmatter + f"# {title}\n\n" + content
        
        # Determine output path
        category_dir = CATEGORIES_DIR / category
        category_dir.mkdir(exist_ok=True)
        
        # Generate filename (use timestamp to avoid conflicts)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_title = re.sub(r'[^\w\u4e00-\u9fff]', '_', title)[:30]
        output_filename = f"{timestamp}_{safe_title}.md"
        output_path = category_dir / output_filename
        
        # Write processed file
        output_path.write_text(processed_content, encoding='utf-8')
        
        # Move original to processed archive
        archive_path = PROCESSED_DIR / filepath.name
        filepath.rename(archive_path)
        
        print(f"✓ 处理: {filepath.name} → {category}/{output_filename}")
        return True
        
    except Exception as e:
        print(f"✗ 错误处理 {filepath.name}: {e}")
        return False

def process_all_inbox():
    """Process all files in inbox."""
    if not INBOX_DIR.exists():
        print(f"Inbox 目录不存在: {INBOX_DIR}")
        return
    
    files = list(INBOX_DIR.glob("*.md"))
    if not files:
        print("Inbox 为空，无需处理")
        return
    
    print(f"发现 {len(files)} 个待处理文件")
    print("=" * 50)
    
    success_count = 0
    for filepath in files:
        if process_inbox_file(filepath):
            success_count += 1
    
    print("=" * 50)
    print(f"处理完成: {success_count}/{len(files)}")

if __name__ == "__main__":
    process_all_inbox()
