"""Built-in protocol fetcher."""

import json
from pathlib import Path
from typing import Tuple

from cokodo_agent.config import BUNDLED_PROTOCOL_VERSION
from cokodo_agent.fetcher.base import (
    BaseFetcher,
    SourceUnavailableError,
)


class BuiltinFetcher(BaseFetcher):
    """Fetch protocol from bundled files in the package."""

    name = "Built-in"

    def __init__(self) -> None:
        # Get the bundled directory path
        self.bundled_path = Path(__file__).parent.parent / "bundled" / "agent"

    def is_available(self) -> bool:
        """Check if bundled protocol exists."""
        manifest_exists = self.bundled_path.exists() and (self.bundled_path / "start-here.md").exists()
        return bool(manifest_exists)

    def fetch(self) -> Tuple[Path, str]:
        """
        Return path to bundled protocol.

        Returns:
            Tuple of (protocol_path, version) where version is the protocol spec
            version from manifest.json (e.g. "3.2.0").
        """
        if not self.is_available():
            raise SourceUnavailableError(
                "Built-in protocol not found. " "The package may be corrupted. Please reinstall."
            )

        spec_version = self._read_spec_version() or BUNDLED_PROTOCOL_VERSION
        return self.bundled_path, spec_version

    def _read_spec_version(self) -> str | None:
        """Read protocol spec version from bundled manifest.json."""
        manifest_path = self.bundled_path / "manifest.json"
        try:
            manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
            v = manifest.get("version")
            return str(v) if v is not None else None
        except (OSError, json.JSONDecodeError, KeyError):
            return None
