"""Read-only access to the SFDX repository on GitHub (tree listing + file contents)."""

from __future__ import annotations

from typing import Dict, List, Optional

import httpx

from packages.config import Settings, get_settings


class GitHubRepoReader:
    """Lists and reads files on the default branch of GIT_REPO_URL."""

    def __init__(
        self,
        settings: Optional[Settings] = None,
        transport: Optional[httpx.AsyncBaseTransport] = None,
    ) -> None:
        self.settings = settings or get_settings()
        self.transport = transport
        parsed = self.settings.github_owner_repo
        if not parsed:
            raise ValueError("GIT_REPO_URL must be set to owner/repo (or GitHub URL)")
        self.owner, self.repo = parsed
        self.branch = self.settings.git_default_branch or "main"
        self._api = self.settings.github_api_base_url.rstrip("/")
        self._paths: Optional[List[str]] = None
        self._files: Dict[str, Optional[str]] = {}

    def _headers(self, accept: str = "application/vnd.github+json") -> Dict[str, str]:
        headers = {"Accept": accept, "X-GitHub-Api-Version": "2022-11-28"}
        if self.settings.github_token:
            headers["Authorization"] = f"Bearer {self.settings.github_token}"
        return headers

    def blob_url(self, path: str) -> str:
        return f"https://github.com/{self.owner}/{self.repo}/blob/{self.branch}/{path}"

    async def list_paths(self) -> List[str]:
        if self._paths is not None:
            return self._paths
        async with httpx.AsyncClient(
            timeout=30.0, headers=self._headers(), transport=self.transport
        ) as client:
            resp = await client.get(
                f"{self._api}/repos/{self.owner}/{self.repo}/git/trees/{self.branch}",
                params={"recursive": "1"},
            )
            resp.raise_for_status()
            data = resp.json()
        self._paths = [
            item["path"]
            for item in data.get("tree") or []
            if item.get("type") == "blob" and item.get("path")
        ]
        return self._paths

    async def read_file(self, path: str) -> Optional[str]:
        if path in self._files:
            return self._files[path]
        async with httpx.AsyncClient(
            timeout=30.0,
            headers=self._headers("application/vnd.github.raw+json"),
            transport=self.transport,
        ) as client:
            resp = await client.get(
                f"{self._api}/repos/{self.owner}/{self.repo}/contents/{path}",
                params={"ref": self.branch},
            )
        if resp.status_code == 404:
            self._files[path] = None
            return None
        resp.raise_for_status()
        self._files[path] = resp.text
        return resp.text


def repo_reader_available(settings: Settings) -> bool:
    return settings.git_provider == "github" and settings.github_owner_repo is not None
