"""Auto-detect and parse AI conversation exports."""

from pathlib import Path
from typing import List, Union

from ..models import Conversation
from .chatgpt import ChatGPTParser
from .claude import ClaudeParser
from .codex import CodexParser
from .gemini import GeminiParser
from .gemini_cli import GeminiCLIParser
from .csv_generic import CSVParser

# Order matters: more specific parsers first
PARSERS = [
    ChatGPTParser(),
    ClaudeParser(),
    CodexParser(),
    GeminiCLIParser(),
    GeminiParser(),
    CSVParser(),
]


def detect_and_parse(path: Union[str, Path]) -> List[Conversation]:
    """Auto-detect format and parse the input file/directory."""
    path = Path(path)
    if not path.exists():
        raise FileNotFoundError(f"Path not found: {path}")

    for parser in PARSERS:
        if parser.can_parse(path):
            convs = parser.parse(path)
            if convs:
                return convs

    raise ValueError(
        f"Cannot detect format for: {path}\n"
        "Supported: ChatGPT, Claude Code, Codex, Gemini CLI, Gemini Web, CSV"
    )
