"""CLI entry point for aipoc — Prompts of Codebase."""
import argparse
import os
import platform
import sys
from pathlib import Path

from poc.aggregator import count_all, list_all_chats
from poc.display import render, render_chats


def _detect_tool_dirs() -> dict[str, Path]:
    """Auto-detect installed AI coding tool data directories."""
    dirs = {}
    home = Path.home()

    # Claude Code: ~/.claude
    claude_dir = home / ".claude"
    if claude_dir.exists():
        dirs["claude"] = claude_dir

    # Codex CLI: ~/.codex
    codex_dir = home / ".codex"
    if codex_dir.exists():
        dirs["codex"] = codex_dir

    # Cursor: platform-specific
    system = platform.system()
    if system == "Darwin":
        cursor_dir = home / "Library" / "Application Support" / "Cursor" / "User"
    elif system == "Linux":
        cursor_dir = home / ".config" / "Cursor" / "User"
    elif system == "Windows":
        appdata = os.environ.get("APPDATA", "")
        cursor_dir = Path(appdata) / "Cursor" / "User" if appdata else None
    else:
        cursor_dir = None

    if cursor_dir and cursor_dir.exists():
        dirs["cursor"] = cursor_dir

    return dirs


def _maybe_show_welcome():
    """Show welcome message on first run."""
    marker = Path.home() / ".aipoc_welcomed"
    if marker.exists():
        return
    print(HELP_TEXT)
    print("  \033[2mThis message is shown once. Run aipoc --help to see it again.\033[0m")
    print()
    try:
        marker.touch()
    except OSError:
        pass


HELP_TEXT = """\
\033[1maipoc — Prompts of Codebase\033[0m
Like \033[2mloc\033[0m counts lines of code, \033[1maipoc\033[0m counts how many AI prompts built your codebase.

\033[1mUsage:\033[0m
  aipoc                    Count prompts for current directory
  aipoc /path/to/project   Count prompts for a specific project
  aipoc --all              Rank all your projects by prompt count
  aipoc --deep             Show every chat session, not just top 10
  aipoc --json             Output machine-readable JSON

\033[1mSupported tools:\033[0m
  \033[36mClaude Code\033[0m   ~/.claude/
  \033[32mCodex CLI\033[0m     ~/.codex/
  \033[35mCursor\033[0m        ~/Library/.../Cursor/  (or ~/.config/Cursor/)

\033[1mExamples:\033[0m
  aipoc                    # how many prompts built this project?
  aipoc --all              # which of my projects used the most AI?
  aipoc ~/my-app --deep    # see every conversation for my-app
  aipoc --json | jq        # pipe to jq for scripting
"""


def main():
    parser = argparse.ArgumentParser(
        prog="aipoc",
        description="Prompts of Codebase — count how many AI prompts built your project",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=HELP_TEXT,
    )
    parser.add_argument(
        "path",
        nargs="?",
        default=".",
        help="Project directory to analyze (default: current directory)",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output raw JSON instead of pretty table",
    )
    parser.add_argument(
        "--all",
        action="store_true",
        help="Show all projects with prompt counts",
    )
    parser.add_argument(
        "--deep",
        action="store_true",
        help="Show all chat sessions (not just top 10)",
    )

    args = parser.parse_args()

    # First-run welcome: show usage if no args given and it's the first time
    if len(sys.argv) == 1:
        _maybe_show_welcome()

    tool_dirs = _detect_tool_dirs()

    if not tool_dirs:
        print("No AI coding tool data found. Looked for:")
        print("  - Claude Code (~/.claude)")
        print("  - Codex CLI (~/.codex)")
        print("  - Cursor (~/.config/Cursor or ~/Library/Application Support/Cursor)")
        sys.exit(1)

    if args.all:
        _show_all(tool_dirs, args.json)
    else:
        project_path = str(Path(args.path).resolve())
        result = count_all(project_path, tool_dirs)

        if args.json:
            import json
            chats = list_all_chats(project_path, tool_dirs)
            result["chats"] = chats
            print(json.dumps(result, indent=2, default=str))
        else:
            print(render(project_path, result))
            # Show chats
            chats = list_all_chats(project_path, tool_dirs)
            limit = len(chats) if args.deep else 10
            print(render_chats(chats, limit=limit))


def _show_all(tool_dirs: dict[str, Path], as_json: bool):
    """Show prompt counts for all known projects."""
    from poc.parsers.claude import count_from_history

    all_projects = set()

    # Gather all project paths from Claude history
    if "claude" in tool_dirs:
        history = tool_dirs["claude"] / "history.jsonl"
        counts = count_from_history(history)
        all_projects.update(counts.keys())

    # Gather from Codex sessions
    if "codex" in tool_dirs:
        import json
        sessions_dir = tool_dirs["codex"] / "sessions"
        if sessions_dir.exists():
            for f in sessions_dir.rglob("rollout-*.jsonl"):
                try:
                    with open(f) as fh:
                        for line in fh:
                            entry = json.loads(line.strip())
                            if entry.get("type") == "session_meta":
                                cwd = entry.get("payload", {}).get("cwd")
                                if cwd:
                                    all_projects.add(cwd)
                                break
                except (json.JSONDecodeError, IOError):
                    continue

    if as_json:
        import json
        results = {}
        for proj in sorted(all_projects):
            results[proj] = count_all(proj, tool_dirs)
        print(json.dumps(results, indent=2, default=str))
    else:
        # Sort by total prompts descending
        project_counts = []
        for proj in all_projects:
            result = count_all(proj, tool_dirs)
            if result["total"] > 0:
                project_counts.append((proj, result["total"]))

        project_counts.sort(key=lambda x: -x[1])

        print()
        print(f"  \033[1maipoc — Prompts of Codebase (all projects)\033[0m")
        print()
        print(f"  {'Prompts':>8}  Project")
        print(f"  {'─' * 8}  {'─' * 50}")
        for proj, count in project_counts[:30]:
            # Shorten path for display
            short = proj.replace(str(Path.home()), "~")
            print(f"  {count:>8}  {short}")
        print()
        total = sum(c for _, c in project_counts)
        print(f"  {total:>8}  TOTAL ({len(project_counts)} projects)")
        print()


if __name__ == "__main__":
    main()
