"""Общая расширяемая JSON-БД Hermes."""

import fcntl
import os
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator

from pydantic import BaseModel, ConfigDict, Field, ValidationError


DEFAULT_DASHBOARD_PORT = 9200
# Порты сайдкара браузера в том же поде: Chromium DevTools и шлюз CDP (services/browser/cdp_gate.py).
RESERVED_POD_PORTS = frozenset({9222, 9223, 9224})


class JsonDbError(RuntimeError):
    """Не удалось прочитать или записать служебную БД."""


class UnknownAgentError(JsonDbError):
    """Для профиля ещё не выделен endpoint `serve`."""


class DashboardAgent(BaseModel):
    model_config = ConfigDict(extra="allow")

    serve_port: int


class DashboardState(BaseModel):
    model_config = ConfigDict(extra="allow")

    # Счётчик из db.json на томах инстансов: читаем, обратно не пишем.
    next_port: int | None = Field(default=None, exclude=True)
    agents: dict[str, DashboardAgent] = Field(default_factory=dict)


class JsonDb(BaseModel):
    model_config = ConfigDict(extra="allow")

    dashboards: DashboardState = Field(default_factory=DashboardState)


def database_path() -> Path:
    return Path.home() / ".agentek" / "db.json"


def _lock_path(path: Path) -> Path:
    return path.with_name("db.lock")


def _read_database(path: Path) -> JsonDb:
    try:
        return JsonDb.model_validate_json(path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return JsonDb()
    except (OSError, ValidationError) as exc:
        raise JsonDbError(f"cannot read JSON database {path}: {exc}") from exc


def _write_database(path: Path, database: JsonDb) -> None:
    temporary = path.with_name(f".{path.name}.tmp")
    try:
        temporary.write_text(database.model_dump_json(indent=2) + "\n", encoding="utf-8")
        os.replace(temporary, path)
    except OSError as exc:
        raise JsonDbError(f"cannot write JSON database {path}: {exc}") from exc
    finally:
        temporary.unlink(missing_ok=True)


@contextmanager
def _locked_database() -> Iterator[tuple[Path, JsonDb]]:
    path = database_path()
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        lock = _lock_path(path).open("a", encoding="utf-8")
    except OSError as exc:
        raise JsonDbError(f"cannot prepare JSON database {path}: {exc}") from exc
    with lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX)
        except OSError as exc:
            raise JsonDbError(f"cannot lock JSON database {path}: {exc}") from exc
        yield path, _read_database(path)


def get_dashboard_port(slug: str) -> int:
    database = _read_database(database_path())
    try:
        return database.dashboards.agents[slug].serve_port
    except KeyError as exc:
        raise UnknownAgentError(f"no dashboard port allocated for agent {slug!r}") from exc


def _allocate_port(state: DashboardState, slug: str) -> int | None:
    if slug in state.agents:
        return None
    state.agents[slug] = DashboardAgent(serve_port=_lowest_free_port(state))
    return state.agents[slug].serve_port


def _lowest_free_port(state: DashboardState) -> int:
    taken = {agent.serve_port for agent in state.agents.values()} | RESERVED_POD_PORTS
    port = DEFAULT_DASHBOARD_PORT
    while port in taken:
        port += 1
    return port


def _move_off_reserved_ports(state: DashboardState) -> bool:
    clashing = [agent for agent in state.agents.values() if agent.serve_port in RESERVED_POD_PORTS]
    for agent in clashing:
        agent.serve_port = _lowest_free_port(state)
    return bool(clashing)


def allocate_dashboard_port(slug: str) -> int:
    with _locked_database() as (path, database):
        allocated = _allocate_port(database.dashboards, slug)
        if allocated is None:
            return database.dashboards.agents[slug].serve_port
        _write_database(path, database)
        return allocated


def ensure_dashboard_ports(slugs: list[str]) -> None:
    """Выдаёт порты профилям без порта и уводит профили с портов сайдкаров; зовётся до старта `serve`."""
    with _locked_database() as (path, database):
        changed = _move_off_reserved_ports(database.dashboards)
        for slug in slugs:
            if _allocate_port(database.dashboards, slug) is not None:
                changed = True
        if changed:
            _write_database(path, database)


def release_dashboard_port(slug: str) -> None:
    """Освобождает порт удалённого профиля: его `serve` к этому моменту должен быть погашен."""
    with _locked_database() as (path, database):
        if database.dashboards.agents.pop(slug, None) is not None:
            _write_database(path, database)
