"""HTTP client for talking to the control plane."""

import httpx

from . import config


def _get_client(env: str | None = None, timeout: int = 30) -> tuple[httpx.Client, dict]:
    env_config = config.get_env_config(env)
    endpoint = env_config.get("endpoint")
    token = env_config.get("access_token")

    if not endpoint:
        raise ValueError(f"No endpoint configured for environment '{config.get_current_env()}'")
    if not token:
        raise ValueError("Not logged in. Run 'loony login' first.")

    client = httpx.Client(
        base_url=endpoint,
        headers={"Authorization": f"Bearer {token}"},
        timeout=timeout,
    )
    return client, env_config


def me(env: str | None = None) -> dict:
    client, _ = _get_client(env)
    resp = client.get("/api/v1/me")
    resp.raise_for_status()
    return resp.json()


def health(env: str | None = None) -> dict:
    env_config = config.get_env_config(env)
    endpoint = env_config.get("endpoint")
    if not endpoint:
        raise ValueError(f"No endpoint configured for environment '{config.get_current_env()}'")

    resp = httpx.get(f"{endpoint}/healthz", timeout=10)
    resp.raise_for_status()
    return resp.json()


def deploy(name: str, payload: dict, env: str | None = None) -> dict:
    # Large script uploads can take well over 30s — use a generous timeout.
    client, _ = _get_client(env, timeout=300)
    resp = client.post(f"/api/v1/services/{name}/deploy", json=payload)
    resp.raise_for_status()
    return resp.json()


def submit_feedback(payload: dict, env: str | None = None) -> dict:
    client, _ = _get_client(env)
    resp = client.post("/api/v1/feedback", json=payload)
    resp.raise_for_status()
    return resp.json()
