"""Aggregates prompt counts across all supported AI coding tools."""
from pathlib import Path

from poc.parsers import claude, codex, cursor


def count_all(project_path: str, tool_dirs: dict[str, Path]) -> dict:
    """Count prompts across all tools for a given project.

    Args:
        project_path: Absolute path to the project directory
        tool_dirs: {"claude": Path, "codex": Path, "cursor": Path}

    Returns: {
        "total": N,
        "by_tool": {
            "claude": {"prompts": N, "sessions": M, ...},
            "codex": {"prompts": N, "sessions": M, ...},
            "cursor": {"prompts": N, "composer_sessions": M, "chat_prompts": P, ...},
        }
    }
    """
    results = {}

    if "claude" in tool_dirs:
        results["claude"] = claude.count_for_project(project_path, tool_dirs["claude"])
    if "codex" in tool_dirs:
        results["codex"] = codex.count_for_project(project_path, tool_dirs["codex"])
    if "cursor" in tool_dirs:
        results["cursor"] = cursor.count_for_project(project_path, tool_dirs["cursor"])

    total = sum(r.get("prompts", 0) for r in results.values())

    return {"total": total, "by_tool": results}


def list_all_chats(project_path: str, tool_dirs: dict[str, Path]) -> list[dict]:
    """List all chats across all tools, sorted by most recent first.

    Each chat dict has at minimum: tool, first_prompt or name, and a sortable date field.
    """
    all_chats = []

    if "claude" in tool_dirs:
        all_chats.extend(claude.list_chats(project_path, tool_dirs["claude"]))
    if "codex" in tool_dirs:
        all_chats.extend(codex.list_chats(project_path, tool_dirs["codex"]))
    if "cursor" in tool_dirs:
        all_chats.extend(cursor.list_chats(project_path, tool_dirs["cursor"]))

    # Normalize sort key: Claude/Codex use ISO strings, Cursor uses epoch ms
    # Convert everything to epoch ms for consistent sorting
    from datetime import datetime, timezone

    def _to_epoch_ms(val) -> float:
        if isinstance(val, (int, float)):
            return float(val)
        if isinstance(val, str) and val:
            try:
                # Parse ISO format like "2025-01-02T10:00:06.000Z"
                dt = datetime.fromisoformat(val.replace("Z", "+00:00"))
                return dt.timestamp() * 1000
            except ValueError:
                return 0.0
        return 0.0

    def sort_key(chat):
        modified = chat.get("modified", chat.get("timestamp", ""))
        return _to_epoch_ms(modified)

    all_chats.sort(key=sort_key, reverse=True)
    return all_chats
