"""HTTP client — thin wrapper around httpx for Nautilus API calls."""
from __future__ import annotations

import httpx
from typing import Any

from quark import config


class QuarkError(Exception):
    def __init__(self, status: int, detail: str):
        self.status = status
        self.detail = detail
        super().__init__(f"HTTP {status}: {detail}")


def _headers() -> dict:
    tok = config.token()
    if not tok:
        raise QuarkError(
            401,
            "No token found. Run `quark login` or set QUARK_TOKEN env var.",
        )
    return {"Authorization": f"Bearer {tok}"}


def _base() -> str:
    return config.api_url().rstrip("/")


def _raise(r: httpx.Response) -> None:
    if r.status_code >= 400:
        try:
            detail = r.json().get("detail", r.text)
        except Exception:
            detail = r.text
        raise QuarkError(r.status_code, str(detail))


# ── Fossils ────────────────────────────────────────────────────────────────────

def fossilize(
    name: str,
    source_prompt: str,
    fossil_type: str = "cognitive_imprint",
    description: str | None = None,
    tags: list[str] | None = None,
    mode: str = "pur",
    timeout: int = 120,
) -> dict:
    payload = {
        "name": name,
        "source_prompt": source_prompt,
        "fossil_type": fossil_type,
        "description": description or "",
        "tags": tags or [],
        "fossilization_mode": mode,
    }
    r = httpx.post(
        f"{_base()}/api/nautilus/fossils/fossilize",
        json=payload,
        headers=_headers(),
        timeout=timeout,
    )
    _raise(r)
    return r.json()


def get_fossil(fossil_id: str) -> dict:
    r = httpx.get(
        f"{_base()}/api/nautilus/fossils/{fossil_id}",
        headers=_headers(),
        timeout=30,
    )
    _raise(r)
    return r.json()


def create_fossil(payload: dict) -> dict:
    r = httpx.post(
        f"{_base()}/api/nautilus/fossils",
        json=payload,
        headers=_headers(),
        timeout=30,
    )
    _raise(r)
    return r.json()


def list_fossils(limit: int = 50) -> list[dict]:
    r = httpx.get(
        f"{_base()}/api/nautilus/fossils",
        params={"limit": limit},
        headers=_headers(),
        timeout=30,
    )
    _raise(r)
    data = r.json()
    # API returns { fossils: [...] } or a list directly
    return data.get("fossils", data) if isinstance(data, dict) else data


def get_versions(fossil_id: str) -> list[dict]:
    r = httpx.get(
        f"{_base()}/api/nautilus/versions",
        params={"fossil_id": fossil_id},
        headers=_headers(),
        timeout=30,
    )
    _raise(r)
    data = r.json()
    return data.get("versions", data) if isinstance(data, dict) else data


# ── Auth ───────────────────────────────────────────────────────────────────────

def login(email: str, password: str) -> dict:
    r = httpx.post(
        f"{_base()}/api/auth/login",
        json={"email": email, "password": password},
        timeout=15,
    )
    _raise(r)
    return r.json()


# ── Health ─────────────────────────────────────────────────────────────────────

def health() -> dict:
    r = httpx.get(f"{_base()}/health", timeout=10)
    _raise(r)
    return r.json()
