"""gui.new Python client."""

from __future__ import annotations

import os
from dataclasses import dataclass
from typing import Optional

import httpx

BASE = os.environ.get("GUI_NEW_URL", "https://gui.new")
_key = lambda: os.environ.get("GUI_NEW_API_KEY", "")


@dataclass
class Canvas:
    id: str
    url: str
    edit_token: str
    expires_at: str
    title: Optional[str] = None

    def open(self):
        """Open canvas URL in browser."""
        import webbrowser
        webbrowser.open(self.url)


def _headers() -> dict:
    h = {"Content-Type": "application/json"}
    key = _key()
    if key:
        h["Authorization"] = f"Bearer {key}"
    return h


def create(
    html: str,
    title: str = "Untitled",
    *,
    base_url: str | None = None,
) -> Canvas:
    """Create a canvas. Returns Canvas with id, url, edit_token."""
    url = (base_url or BASE) + "/api/canvas"
    r = httpx.post(url, json={"html": html, "title": title}, headers=_headers(), timeout=30)
    r.raise_for_status()
    d = r.json()
    return Canvas(
        id=d["id"],
        url=d.get("url", f"{base_url or BASE}/{d['id']}"),
        edit_token=d["editToken"],
        expires_at=d["expiresAt"],
        title=title,
    )


def update(
    id: str,
    html: str,
    edit_token: str,
    *,
    title: str | None = None,
    base_url: str | None = None,
) -> dict:
    """Update a canvas's HTML (requires edit_token)."""
    url = f"{base_url or BASE}/api/canvas/{id}"
    body: dict = {"html": html, "editToken": edit_token}
    if title is not None:
        body["title"] = title
    r = httpx.put(url, json=body, headers=_headers(), timeout=30)
    r.raise_for_status()
    return r.json()


def get(id: str, *, base_url: str | None = None) -> dict:
    """Get canvas metadata (no HTML body)."""
    url = f"{base_url or BASE}/api/canvas/{id}"
    r = httpx.get(url, headers=_headers(), timeout=30)
    r.raise_for_status()
    return r.json()


def extend(id: str, edit_token: str, *, base_url: str | None = None) -> dict:
    """Extend canvas expiry by 24h."""
    url = f"{base_url or BASE}/api/canvas/{id}/extend"
    r = httpx.post(url, json={"editToken": edit_token}, headers=_headers(), timeout=30)
    r.raise_for_status()
    return r.json()


def delete(id: str, edit_token: str, *, base_url: str | None = None) -> None:
    """Delete a canvas."""
    url = f"{base_url or BASE}/api/canvas/{id}"
    r = httpx.request("DELETE", url, json={"editToken": edit_token}, headers=_headers(), timeout=30)
    r.raise_for_status()
