"""Generic CSV parser for manually organized conversation data."""

import csv
from datetime import datetime
from pathlib import Path
from typing import List
from collections import defaultdict

from .base import BaseParser
from ..models import Conversation, Message


class CSVParser(BaseParser):
    def can_parse(self, path: Path) -> bool:
        if not path.is_file() or path.suffix != ".csv":
            return False
        try:
            with open(path, encoding="utf-8") as f:
                reader = csv.DictReader(f)
                fields = reader.fieldnames or []
                return "role" in fields and "content" in fields
        except Exception:
            return False

    def parse(self, path: Path) -> List[Conversation]:
        with open(path, encoding="utf-8") as f:
            reader = csv.DictReader(f)
            rows = list(reader)

        # Group by conversation_id
        groups = defaultdict(list)
        for row in rows:
            conv_id = row.get("conversation_id", "default")
            groups[conv_id].append(row)

        conversations = []
        for conv_id, conv_rows in groups.items():
            messages = []
            earliest_ts = None

            for row in conv_rows:
                role = row.get("role", "")
                content = row.get("content", "")
                if role not in ("user", "assistant") or not content:
                    continue

                ts = None
                ts_str = row.get("timestamp", "")
                if ts_str:
                    for fmt in ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%SZ"):
                        try:
                            ts = datetime.strptime(ts_str, fmt)
                            break
                        except ValueError:
                            continue

                messages.append(Message(role=role, content=content, timestamp=ts))

                if ts and (earliest_ts is None or ts < earliest_ts):
                    earliest_ts = ts

            if messages:
                conversations.append(Conversation(
                    id=conv_id,
                    title=messages[0].content[:50] if messages else "",
                    messages=messages,
                    created=earliest_ts,
                    platform="csv",
                ))

        conversations.sort(key=lambda c: c.created or datetime.min)
        return conversations
