"""Google Gemini CLI local session JSON parser."""

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

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


class GeminiCLIParser(BaseParser):
    def can_parse(self, path: Path) -> bool:
        if path.is_dir():
            # ~/.gemini or a directory containing Gemini CLI sessions
            return bool(list(path.glob("**/chats/session-*.json")))
        if path.is_file() and path.suffix == ".json":
            try:
                with open(path, encoding="utf-8") as f:
                    data = json.load(f)
                # Gemini CLI format: single object with sessionId + messages
                return (
                    isinstance(data, dict)
                    and "sessionId" in data
                    and "messages" in data
                )
            except (json.JSONDecodeError, IOError):
                pass
        return False

    def parse(self, path: Path) -> List[Conversation]:
        if path.is_dir():
            convs = []
            for json_file in sorted(path.glob("**/chats/session-*.json")):
                conv = self._parse_session(json_file)
                if conv:
                    convs.append(conv)
            convs.sort(key=lambda c: c.created or datetime.min)
            return convs
        elif path.is_file():
            conv = self._parse_session(path)
            return [conv] if conv else []
        return []

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

        messages = []
        for msg in data.get("messages", []):
            msg_type = msg.get("type", "")
            ts = self._parse_ts(msg.get("timestamp"))

            if msg_type == "user":
                content = self._extract_user_text(msg.get("content", []))
                if content:
                    messages.append(Message(role="user", content=content, timestamp=ts))

            elif msg_type == "gemini":
                content = msg.get("content", "")
                if isinstance(content, str) and content.strip():
                    messages.append(Message(role="assistant", content=content, timestamp=ts))

        if not messages:
            return None

        created = self._parse_ts(data.get("startTime"))

        return Conversation(
            id=data.get("sessionId", path.stem),
            title=messages[0].content[:50] if messages else "",
            messages=messages,
            created=created,
            platform="gemini_cli",
        )

    def _extract_user_text(self, content) -> str:
        """Extract text from Gemini CLI user message content."""
        if isinstance(content, str):
            return content
        if isinstance(content, list):
            for item in content:
                if isinstance(item, dict) and item.get("text"):
                    return item["text"]
                elif isinstance(item, str):
                    return item
        return ""

    def _parse_ts(self, ts_str) -> Optional[datetime]:
        if not ts_str:
            return None
        try:
            return datetime.fromisoformat(ts_str.replace("Z", "+00:00")).replace(tzinfo=None)
        except (ValueError, TypeError):
            return None
