"""Command-line interface."""

import argparse
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import List, Tuple

from .models import Conversation, Message
from .parsers import detect_and_parse
from .analyzer import analyze
from .report import generate_all


# Known AI CLI data locations and their file patterns
AUTO_DISCOVER_PATHS = [
    ("Claude Code", Path.home() / ".claude", "**/sessions-index.json"),
    ("Codex",       Path.home() / ".codex", "sessions/**/*.jsonl"),
    ("Gemini CLI",  Path.home() / ".gemini", "**/chats/session-*.json"),
]


def auto_discover() -> List[Tuple[str, Path]]:
    """Find locally installed AI CLI conversation data."""
    found = []
    for name, path, pattern in AUTO_DISCOVER_PATHS:
        if path.exists() and path.is_dir():
            sessions = list(path.glob(pattern))
            if sessions:
                found.append((name, path))
    return found


def main():
    parser = argparse.ArgumentParser(
        prog="ai-checkup",
        description="Analyze your AI conversations and generate a six-dimension ability radar chart.",
    )
    parser.add_argument(
        "input",
        nargs="?",
        help="Path to conversation export file or directory",
    )
    parser.add_argument(
        "-o", "--output",
        default="ai_checkup_report",
        help="Output directory (default: ai_checkup_report)",
    )
    parser.add_argument(
        "--auto",
        action="store_true",
        help="Auto-discover local AI conversation data (Claude Code, etc.)",
    )
    parser.add_argument(
        "--mock",
        action="store_true",
        help="Run with built-in demo data (no input file needed)",
    )

    args = parser.parse_args()

    if args.mock:
        conversations = generate_mock_data()
        print(f"[Demo Mode] 生成 {len(conversations)} 条模拟对话")
    elif args.auto:
        conversations = _run_auto_discover()
    elif args.input:
        input_path = Path(args.input)
        print(f"解析: {input_path}")
        conversations = detect_and_parse(input_path)
        print(f"解析成功: {len(conversations)} 条对话")
    else:
        # Default to auto-discover if no arguments
        conversations = _run_auto_discover()

    if not conversations:
        print("错误: 未找到有效对话数据")
        print()
        print("用法:")
        print("  ai-checkup --auto                 # 自动扫描本地 AI 对话")
        print("  ai-checkup conversations.json     # 分析 ChatGPT 导出")
        print("  ai-checkup ~/.claude               # 分析 Claude Code 数据")
        print("  ai-checkup --mock                  # 内置演示数据")
        sys.exit(1)

    print("分析中...")
    result = analyze(conversations)

    output_dir = Path(args.output)
    print(f"生成报告 → {output_dir}/")
    generate_all(result, output_dir)

    _print_summary(result, output_dir)


def _run_auto_discover() -> List[Conversation]:
    """Auto-discover and parse local AI data."""
    found = auto_discover()
    if not found:
        print("未发现本地 AI 对话数据。")
        print("当前支持: Claude Code (~/.claude), Codex (~/.codex), Gemini CLI (~/.gemini)")
        print()
        return []

    all_convs = []
    for name, path in found:
        print(f"发现 {name} 数据: {path}")
        try:
            convs = detect_and_parse(path)
            print(f"  → {len(convs)} 条对话")
            all_convs.extend(convs)
        except (ValueError, FileNotFoundError) as e:
            print(f"  → 解析失败: {e}")

    return all_convs


def _print_summary(result, output_dir):
    """Print results summary to terminal."""
    print()
    print("=== AI Checkup 完成 ===")
    print()
    for key in ["questioning", "judgment", "hands_on", "deep_thinking", "execution", "narrative"]:
        dim = result.dimensions[key]
        filled = int(dim.score / 5)
        bar = "█" * filled + "░" * (20 - filled)
        print(f"  {dim.name:4s} {bar} {dim.score:5.1f}")
    print()
    print(f"输出文件:")
    print(f"  {output_dir}/radar.png    — 雷达图")
    print(f"  {output_dir}/report.md    — 分析报告")
    print(f"  {output_dir}/data.json    — 原始数据")


def generate_mock_data() -> List[Conversation]:
    """Generate demo conversations spanning 4 weeks."""
    base = datetime(2026, 1, 5, 10, 0, 0)
    prompts = [
        # Week 1 (Jan 5-11)
        ("帮我写一个Python爬虫脚本", 0),
        ("如何配置nginx反向代理", 1),
        ("什么是微服务架构？和单体架构有什么区别", 2),
        ("我觉得应该用React而不是Vue，帮我对比一下", 3),
        ("帮我部署这个应用到服务器上", 4),
        # Week 2 (Jan 12-18)
        ("修复这个bug，用户登录时报错500", 7),
        ("分析一下这段代码的性能瓶颈", 8),
        ("为什么RESTful API比GraphQL更受欢迎？", 9),
        ("我认为这个方案不合理，先不做缓存层，换个思路", 10),
        ("创建一个完整的用户管理CRUD模块", 11),
        # Week 3 (Jan 19-25)
        ("对比TensorFlow和PyTorch的优缺点", 14),
        ("为什么深度学习需要那么多数据？本质原因是什么", 15),
        ("复盘一下上个月的技术决策，总结经验教训", 16),
        ("不对，这个系统设计有问题，先考虑扩展性再优化性能", 17),
        ("写一篇关于AI编程实践的公众号文章", 18),
        # Week 4 (Jan 26-Feb 1)
        ("评估一下这个技术方案的可行性和风险", 21),
        ("为什么我们的系统在高峰期总是崩溃？根本原因是什么", 22),
        ("设计一个方法论框架来评估不同技术选型的优劣", 23),
        ("反思这次项目延期的教训，总结经验避免重蹈覆辙", 24),
        ("把这个架构设计方案写成一篇技术说明文档发布出去", 25),
    ]

    conversations = []
    for i, (prompt, day_offset) in enumerate(prompts):
        ts = base + timedelta(days=day_offset, hours=i % 8)
        conversations.append(Conversation(
            id=f"mock-{i+1:03d}",
            title=prompt[:30],
            messages=[
                Message(role="user", content=prompt, timestamp=ts),
                Message(role="assistant", content=f"[Demo response to: {prompt[:20]}...]", timestamp=ts),
            ],
            created=ts,
            platform="demo",
        ))

    return conversations
