"""GPAI API client."""

import time

import httpx

from gpai_cli.config import get_api_url, get_token


class GPAIClient:
    def __init__(self) -> None:
        self.base_url = get_api_url()
        self.token = get_token()
        if not self.token:
            raise RuntimeError("Not logged in. Run: gpai login")

    def _headers(self) -> dict[str, str]:
        return {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json",
        }

    def upload_file(self, file_path: str) -> str:
        """Upload an image file and return the file ID."""
        import mimetypes
        from pathlib import Path

        path = Path(file_path)
        mime = mimetypes.guess_type(file_path)[0] or "image/png"
        with open(file_path, "rb") as f:
            files = {"file": (path.name, f, mime)}
            with httpx.Client(timeout=30) as client:
                resp = client.post(
                    f"{self.base_url}/api/files/upload-direct",
                    headers={"Authorization": f"Bearer {self.token}"},
                    files=files,
                )
                resp.raise_for_status()
                data = resp.json()
                return data["fileId"]

    def create_task(self, file_id: str) -> dict:
        """Create a solver task and return the task response."""
        payload = {
            "problems": [{"fileId": file_id}],
            "solverType": "STEP_BY_STEP",
            "title": "CLI Solve",
            "subject": "math",
        }
        with httpx.Client(timeout=30) as client:
            resp = client.post(
                f"{self.base_url}/api/solver/task",
                headers=self._headers(),
                json=payload,
            )
            resp.raise_for_status()
            return resp.json()

    def get_task(self, task_id: str) -> dict:
        """Poll task status."""
        with httpx.Client(timeout=30) as client:
            resp = client.get(
                f"{self.base_url}/api/solver/task/{task_id}",
                headers=self._headers(),
            )
            resp.raise_for_status()
            return resp.json()

    def get_problem_solution(self, task_id: str, problem_id: str) -> dict:
        """Get the solution for a specific problem."""
        with httpx.Client(timeout=30) as client:
            resp = client.get(
                f"{self.base_url}/api/solver/task/{task_id}/problem/{problem_id}",
                headers=self._headers(),
            )
            resp.raise_for_status()
            return resp.json()

    def wait_for_completion(
        self, task_id: str, poll_interval: float = 2.0, timeout: float = 180.0
    ) -> dict:
        """Poll until task completes or fails."""
        start = time.time()
        while time.time() - start < timeout:
            task = self.get_task(task_id)
            status = task.get("task", {}).get("status", "")
            if status in ("completed", "failed"):
                return task
            time.sleep(poll_interval)
        raise TimeoutError(f"Task {task_id} did not complete within {timeout}s")
