"""Gemini Chrome extension export 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 GeminiParser(BaseParser):
    def can_parse(self, path: Path) -> bool:
        if not path.is_file() or path.suffix != ".json":
            return False
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            if not isinstance(data, list) or len(data) == 0:
                return False
            first = data[0]
            # Gemini exports have "messages" array with role/content
            # but NOT "mapping" (which is ChatGPT)
            return "messages" in first and "mapping" not in first
        except (json.JSONDecodeError, KeyError, IndexError):
            return False

    def parse(self, path: Path) -> List[Conversation]:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)

        conversations = []
        for item in data:
            messages = []
            for msg in item.get("messages", []):
                role = msg.get("role", "")
                content = msg.get("content", "")
                if role in ("user", "assistant") and content:
                    ts = None
                    ts_str = msg.get("timestamp", msg.get("created", ""))
                    if ts_str:
                        try:
                            ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
                            ts = ts.replace(tzinfo=None)
                        except ValueError:
                            pass
                    messages.append(Message(role=role, content=content, timestamp=ts))

            if not messages:
                continue

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

            conv = Conversation(
                id=item.get("id", ""),
                title=item.get("title", ""),
                messages=messages,
                created=created,
                platform="gemini",
            )
            conversations.append(conv)

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