"""REST serve: порт и токен те же, что у WS; без `profile` он открывает свой state.db — ровно нужный."""
import httpx

from app import dashboard_client as dc
from app.json_db import get_dashboard_port

_TIMEOUT = 15.0


def _base(slug: str) -> str:
    return f"http://127.0.0.1:{get_dashboard_port(slug)}"


def _headers() -> dict:
    return {"Authorization": f"Bearer {dc.session_token()}"}


# Движок отдаёт страницу не больше сотни и на большее отвечает 422 — консоль просит двести.
_SERVE_PAGE_LIMIT = 100


async def list_sessions(slug: str, *, limit: int, offset: int, exclude_sources: str) -> dict:
    """Список сессий страницами движка: сколько попросили, столько и отдаём.

    Клеим страницы здесь, а не режем запрос: обрезанный список выглядит как «чатов больше нет».
    """
    sessions: list[dict] = []
    total = None
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        while len(sessions) < limit:
            params = {"limit": min(_SERVE_PAGE_LIMIT, limit - len(sessions)),
                      "offset": offset + len(sessions), "order": "recent"}
            if exclude_sources:
                params["exclude_sources"] = exclude_sources
            resp = await client.get(f"{_base(slug)}/api/sessions", params=params, headers=_headers())
            resp.raise_for_status()
            page = resp.json()
            rows = page.get("sessions") or []
            total = page.get("total", total)
            sessions.extend(rows)
            if len(rows) < params["limit"]:
                break
    return {"sessions": sessions, "total": total}


async def get_session(slug: str, session_id: str) -> dict | None:
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        resp = await client.get(f"{_base(slug)}/api/sessions/{session_id}", headers=_headers())
        if resp.status_code == 404:
            return None
        resp.raise_for_status()
        return resp.json()


async def rename_session(slug: str, session_id: str, title: str) -> dict | None:
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        resp = await client.patch(
            f"{_base(slug)}/api/sessions/{session_id}", json={"title": title}, headers=_headers(),
        )
        if resp.status_code == 404:
            return None
        resp.raise_for_status()
    return await get_session(slug, session_id)


async def delete_session(slug: str, session_id: str) -> None:
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        resp = await client.delete(f"{_base(slug)}/api/sessions/{session_id}", headers=_headers())
        resp.raise_for_status()


async def _cron(method: str, slug: str, path: str, *, json: dict | None = None) -> httpx.Response:
    # Без profile serve смотрит кроны ВСЕХ профилей инстанса, даже запущенный --isolated.
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        return await client.request(
            method, f"{_base(slug)}/api/cron{path}", params={"profile": slug}, json=json, headers=_headers(),
        )


def _job_or_none(resp: httpx.Response) -> dict | None:
    if resp.status_code == 404:
        return None
    resp.raise_for_status()
    return resp.json()


async def list_cron_jobs(slug: str) -> list:
    resp = await _cron("GET", slug, "/jobs")
    resp.raise_for_status()
    return resp.json()


async def get_cron_job(slug: str, job_id: str) -> dict | None:
    return _job_or_none(await _cron("GET", slug, f"/jobs/{job_id}"))


async def create_cron_job(slug: str, body: dict) -> dict:
    resp = await _cron("POST", slug, "/jobs", json=body)
    resp.raise_for_status()
    return resp.json()


async def update_cron_job(slug: str, job_id: str, updates: dict) -> dict | None:
    return _job_or_none(await _cron("PUT", slug, f"/jobs/{job_id}", json={"updates": updates}))


async def delete_cron_job(slug: str, job_id: str) -> bool:
    resp = await _cron("DELETE", slug, f"/jobs/{job_id}")
    if resp.status_code == 404:
        return False
    resp.raise_for_status()
    return True


async def cron_job_action(slug: str, job_id: str, action: str) -> dict | None:
    """action: pause | resume | trigger. None — джобы нет."""
    return _job_or_none(await _cron("POST", slug, f"/jobs/{job_id}/{action}"))
