"""Claude Code sessions-index.json parser."""

import json
from datetime import datetime
from pathlib import Path
from typing import List

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


class ClaudeParser(BaseParser):
    def can_parse(self, path: Path) -> bool:
        if path.is_file() and path.suffix == ".json":
            try:
                with open(path, encoding="utf-8") as f:
                    data = json.load(f)
                # Claude sessions-index has "entries" list with "firstPrompt" fields
                if isinstance(data, dict) and "entries" in data:
                    entries = data["entries"]
                    if isinstance(entries, list) and len(entries) > 0:
                        return "firstPrompt" in entries[0] or "sessionId" in entries[0]
            except (json.JSONDecodeError, IOError):
                pass
            return False
        if path.is_dir():
            return bool(list(path.glob("**/sessions-index.json")))
        return False

    def parse(self, path: Path) -> List[Conversation]:
        if path.is_file():
            return self._parse_file(path)
        if path.is_dir():
            conversations = []
            for index_file in path.glob("**/sessions-index.json"):
                conversations.extend(self._parse_file(index_file))
            conversations.sort(key=lambda c: c.created or datetime.min)
            return conversations
        return []

    def _parse_file(self, path: Path) -> List[Conversation]:
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
        except (json.JSONDecodeError, IOError):
            return []

        conversations = []
        for entry in data.get("entries", []):
            first_prompt = entry.get("firstPrompt", "")
            if not first_prompt:
                continue

            created_str = entry.get("created", "")
            created = None
            if created_str:
                try:
                    created = datetime.fromisoformat(created_str.replace("Z", "+00:00"))
                    created = created.replace(tzinfo=None)
                except ValueError:
                    pass

            # Claude metadata only has firstPrompt, create a single-message conversation
            messages = [Message(role="user", content=first_prompt, timestamp=created)]

            conv = Conversation(
                id=entry.get("sessionId", ""),
                title=entry.get("summary", first_prompt[:50]),
                messages=messages,
                created=created,
                platform="claude",
                metadata={
                    "message_count": entry.get("messageCount", 0),
                    "project_path": entry.get("projectPath", ""),
                },
            )
            conversations.append(conv)

        return conversations
