"""Reverse-proxy слой: /agents/{slug}/sessions* -> api_server gateway'я профиля на localhost.

Порт профиля назначается провиженом (write_profile_port) и живёт в
profiles/<slug>/.env — gateway читает его из env (override бьёт контейнерный
API_SERVER_PORT), мы читаем оттуда же без subprocess. Дефолтный профиль
(директор) сидит на встроенном дефолте hermes 8642 (контейнерный env снят).
"""
import fcntl
import hashlib
import json
import os
import re
import stat
from collections.abc import Callable
from contextlib import contextmanager
from pathlib import Path

import httpx
import yaml

DEFAULT_PROFILE = "default"
DEFAULT_API_PORT = 8642
# Диапазон профильных портов; ниже 18001 живут служебные порты образа (8642, 8770).
PROFILE_PORT_RANGE_START = 18001

# Ответ агента в /chat занимает минуты; остальное — обычные CRUD-запросы.
CHAT_TIMEOUT = 600.0
DEFAULT_TIMEOUT = 30.0

_PORT_RE = re.compile(r"^API_SERVER_PORT=(\d+)\s*$", re.MULTILINE)
# hermes пишет не-секреты (API_SERVER_PORT) в config.yaml; регулярка для плоского top-level ключа.
# pyyaml не тянем — ключ пишем сами и его формат знаем: `API_SERVER_PORT: NNN` (опц. кавычки).
_YAML_PORT_RE = re.compile(r"^API_SERVER_PORT:\s*[\"']?(\d+)[\"']?\s*$", re.MULTILINE)
# Слаги профилей — плоские имена; всё другое (.., слэши) — попытка выйти из profiles/.
SLUG_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
_PLATFORM_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
# Блоки Telegram в порядке, в каком загрузчик gateway берёт из них allow_from: первый найденный закрывает остальные.
_TELEGRAM_BLOCKS = (("telegram",), ("gateway", "platforms", "telegram"), ("platforms", "telegram"))
# Групповой список консоль не ведёт: доступ в группах задают allowed_chats и allow_from.
_TELEGRAM_FOREIGN_KEYS = ("allow_from", "group_allow_from")


def _env_port(env_path: Path) -> int | None:
    if not env_path.exists():
        return None
    match = _PORT_RE.search(env_path.read_text(encoding="utf-8"))
    return int(match.group(1)) if match else None


def _config_yaml_port(yaml_path: Path) -> int | None:
    # Fallback для агентов, провиженных до перехода на .env (hermes `config set`
    # клал не-секреты в config.yaml). gateway порт оттуда не берёт — только бридж.
    if not yaml_path.exists():
        return None
    match = _YAML_PORT_RE.search(yaml_path.read_text(encoding="utf-8"))
    return int(match.group(1)) if match else None


def _require_slug(slug: str) -> str:
    """Слаг едет в путь, поэтому проверку держат резолверы путей: мимо них папку профиля не собрать."""
    if not SLUG_RE.fullmatch(slug):
        raise ValueError(f"invalid slug: {slug!r}")
    return slug


def _profile_dir(home: Path, slug: str) -> Path:
    return home / "profiles" / _require_slug(slug)


def _profile_env_path(home: Path, slug: str) -> Path:
    # Директор (default) — в корне HERMES_HOME, остальные — profiles/<slug>.
    return home / ".env" if slug == DEFAULT_PROFILE else _profile_dir(home, slug) / ".env"


def _upsert_env(env_path: Path, key: str, value: str) -> None:
    text = env_path.read_text(encoding="utf-8") if env_path.exists() else ""
    new_line = f"{key}={value}"
    lines = text.splitlines()
    for i, line in enumerate(lines):
        if line.startswith(f"{key}="):
            lines[i] = new_line
            break
    else:
        lines.append(new_line)
    env_path.parent.mkdir(parents=True, exist_ok=True)
    tmp = env_path.with_name(".env.tmp")
    tmp.write_text("\n".join(lines) + "\n", encoding="utf-8")
    tmp.replace(env_path)


def write_profile_port(home: Path, slug: str, port: int) -> None:
    """Записать назначенный порт в profiles/<slug>/.env — единственный источник,
    который реально читает gateway.

    api_server резолвит порт из os.environ; профильный .env грузится с override=True
    и бьёт унаследованный контейнерный API_SERVER_PORT. hermes `config set` кладёт
    не-секреты в config.yaml, откуда gateway порт НЕ берёт, — поэтому пишем .env сами.
    """
    _upsert_env(_profile_dir(home, slug) / ".env", "API_SERVER_PORT", str(port))


def write_profile_env(home: Path, slug: str, key: str, value: str) -> None:
    # Для ключей, что gateway/cron читают из env, а не config.yaml (см. вызовы).
    _upsert_env(_profile_env_path(home, slug), key, value)


def _parse_env(env_path: Path) -> list[tuple[str, str]]:
    if not env_path.exists():
        return []
    pairs: list[tuple[str, str]] = []
    for line in env_path.read_text(encoding="utf-8").splitlines():
        if not line or "=" not in line:
            continue
        key, _, value = line.partition("=")
        pairs.append((key, value))
    return pairs


def list_profile_env_names(home: Path, slug: str) -> list[str]:
    return [key for key, _ in _parse_env(_profile_env_path(home, slug))]


def read_profile_env_value(home: Path, slug: str, key: str) -> str | None:
    # INTERNAL — never exposed to the backend directly.
    for k, value in _parse_env(_profile_env_path(home, slug)):
        if k == key:
            return value
    return None


def delete_profile_env(home: Path, slug: str, key: str) -> None:
    env_path = _profile_env_path(home, slug)
    pairs = [(k, v) for k, v in _parse_env(env_path) if k != key]
    env_path.parent.mkdir(parents=True, exist_ok=True)
    tmp = env_path.with_name(".env.tmp")
    tmp.write_text("".join(f"{k}={v}\n" for k, v in pairs), encoding="utf-8")
    tmp.replace(env_path)


def _profile_config_path(home: Path, slug: str) -> Path:
    return home / "config.yaml" if slug == DEFAULT_PROFILE else _profile_dir(home, slug) / "config.yaml"


def profile_initialized(home: Path, slug: str) -> bool:
    if slug == DEFAULT_PROFILE:
        return True
    profile = _profile_dir(home, slug)
    # create_profile сеет .env; delete_profile оставляет profiles/.deleted/<slug>.
    # https://github.com/NousResearch/hermes-agent/blob/29112bef/hermes_constants.py#L297-L302
    return (profile / ".env").is_file() and not (home / "profiles" / ".deleted" / slug).exists()


def _load_config(path: Path) -> dict:
    if not path.exists():
        return {}
    return yaml.safe_load(path.read_text(encoding="utf-8")) or {}


# Читаем-правим-пишем под advisory-локом на самом файле. Гейтвей и `hermes config set` этот лок НЕ
# берут (у Hermes только внутрипроцессный threading.RLock), так что от гонки с движком он не спасает —
# но снимает нашу собственную: два оператора разом, или правка MCP и набора инструментов внахлёст.
@contextmanager
def _config_write_lock(path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)
    lock_path = path.with_name(f"{path.name}.lock")
    with open(lock_path, "a+") as handle:
        fcntl.flock(handle, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(handle, fcntl.LOCK_UN)


def _save_config(path: Path, data: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name("config.yaml.tmp")
    tmp.write_text(
        yaml.safe_dump(data, sort_keys=False, allow_unicode=True, default_flow_style=False),
        encoding="utf-8",
    )
    # Права переносим с оригинала: в конфиге лежат ключи провайдеров, а у директора он 0640 —
    # свежий временный файл пришёл бы с umask-дефолтом и тихо открыл его на чтение всем.
    try:
        os.chmod(tmp, stat.S_IMODE(path.stat().st_mode))
    except FileNotFoundError:
        pass  # файла ещё нет — режим задаст umask, секретов в нём тоже пока нет
    tmp.replace(path)


def _transport_of(cfg: dict) -> str:
    return "http" if cfg.get("url") else "stdio"


def read_profile_mcp(home: Path, slug: str) -> list[dict]:
    servers = _load_config(_profile_config_path(home, slug)).get("mcp_servers") or {}
    out = []
    for name, cfg in servers.items():
        cfg = cfg or {}
        entry = {"name": name, "transport": _transport_of(cfg), "enabled": cfg.get("enabled", True)}
        if cfg.get("url"):
            entry["url"] = cfg["url"]
        if cfg.get("command"):
            entry["command"] = cfg["command"]
        entry["config"] = dict(cfg)
        out.append(entry)
    return out


def mcp_uses_env(home: Path, slug: str, key: str) -> bool:
    """Подставлен ли ключ хоть в один включённый MCP-сервер профиля — `${KEY}` или `${env:KEY}`, как их раскрывает движок."""
    if not SLUG_RE.fullmatch(slug):
        raise ValueError(f"invalid slug: {slug!r}")
    reference = re.compile(r"\$\{(?:env:)?" + re.escape(key) + r"\}")
    servers = _load_config(_profile_config_path(home, slug)).get("mcp_servers") or {}
    return any(
        (cfg or {}).get("enabled", True) and reference.search(json.dumps(cfg, ensure_ascii=False, default=str))
        for cfg in servers.values()
    )


def hermes_home() -> Path:
    """Home по env — для модулей, которым его неоткуда получить параметром (session_ws).
    Читаем на каждом вызове: тесты подменяют переменную после импорта."""
    return Path(os.environ.get("HERMES_HOME", "/opt/data"))


# Отпечаток по (mtime, size) файла: его считают перед каждым ходом, а config.yaml между ходами
# обычно не меняется — так на ход приходится один stat вместо чтения и разбора YAML.
_tools_signature_cache: dict[str, tuple[int, int, str]] = {}


def tools_signature(home: Path, slug: str) -> str:
    """Отпечаток набора тулов профиля: меняется, когда MCP-сервер добавили, убрали или переписали
    и когда включили или выключили тулсет.

    Пустая строка — конфига профиля нет, и синхронизировать нечего.
    """
    path = _profile_config_path(home, slug)
    try:
        st = path.stat()
    except OSError:
        return ""
    key = str(path)
    cached = _tools_signature_cache.get(key)
    if cached and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
        return cached[2]
    config = _load_config(path)
    tool_set = {
        "mcp_servers": config.get("mcp_servers") or {},
        "disabled_toolsets": (config.get("agent") or {}).get("disabled_toolsets") or [],
    }
    payload = json.dumps(tool_set, sort_keys=True, ensure_ascii=False, default=str)
    signature = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
    _tools_signature_cache[key] = (st.st_mtime_ns, st.st_size, signature)
    return signature


def put_profile_mcp(home: Path, slug: str, name: str, config: dict) -> None:
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        data.setdefault("mcp_servers", {})[name] = config
        _save_config(path, data)


def set_profile_mcp_enabled(home: Path, slug: str, name: str, enabled: bool) -> None:
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        servers = data.get("mcp_servers") or {}
        if name not in servers:
            raise ValueError(f"unknown mcp server: {name!r}")
        entry = servers[name] or {}
        entry["enabled"] = enabled
        servers[name] = entry
        data["mcp_servers"] = servers
        _save_config(path, data)


def delete_profile_mcp(home: Path, slug: str, name: str) -> None:
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        servers = data.get("mcp_servers") or {}
        if servers.pop(name, None) is not None:
            data["mcp_servers"] = servers
            _save_config(path, data)


# Набор инструментов агента: глобальный вычет `agent.disabled_toolsets`. Он применяется последним
# и ко всем платформам сразу (веб-чат, мессенджеры, крон, api_server, плагинные) — поэтому одна
# запись, а не набор на каждую платформу в `platform_toolsets`.
# Вычитать он умеет, а включать выключенное по умолчанию — нет: список на стороне консоли собран
# только из включённых по умолчанию тулсетов.
def read_profile_disabled_toolsets(home: Path, slug: str) -> list[str]:
    agent = _load_config(_profile_config_path(home, slug)).get("agent") or {}
    disabled = agent.get("disabled_toolsets") or []
    # `hermes config set` кладёт список строкой, и такая строка молча не срабатывает: итерация по
    # ней даёт символы. Наружу отдаём только настоящий список — иначе покажем набор, которого нет.
    if not isinstance(disabled, list):
        return []
    return [str(name) for name in disabled]


def write_profile_disabled_toolsets(home: Path, slug: str, names: list[str]) -> None:
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        agent = data.get("agent") or {}
        if names:
            agent["disabled_toolsets"] = sorted(set(names))
        else:
            agent.pop("disabled_toolsets", None)
        data["agent"] = agent
        _save_config(path, data)


def update_profile_disabled_skills(home: Path, slug: str, mutate: Callable[[set[str]], set[str]]) -> None:
    """Прочитать `skills.disabled` профиля, применить `mutate` и записать — под одним локом файла.

    Ключ на профиль один, а щёлкают по скиллам параллельно: раздельные чтение и запись дали бы
    двум тумблерам один и тот же старый список, и второй вернул бы то, что снял первый.
    Сам ключ переживает пересев бандла и ре-провижининг: посев трогает папки, конфиг не трогает.
    """
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        skills = data.get("skills") or {}
        stored = skills.get("disabled")
        current = {str(name) for name in stored} if isinstance(stored, list) else set()
        updated = mutate(current)
        if updated == current:
            return
        skills["disabled"] = sorted(updated)
        data["skills"] = skills
        _save_config(path, data)


def set_profile_config_values(home: Path, slug: str, values: dict[str, object]) -> None:
    """Записать точечные ключи config.yaml по их путям («curator.enabled») одной правкой файла."""
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        for dotted, value in values.items():
            *parents, leaf = dotted.split(".")
            section = data
            for key in parents:
                nested = section.get(key)
                section[key] = nested if isinstance(nested, dict) else {}
                section = section[key]
            section[leaf] = value
        _save_config(path, data)


def unset_profile_config_values(home: Path, slug: str, keys: list[str]) -> None:
    """Убрать ключи config.yaml по их путям одной правкой файла; опустевшие секции остаются."""
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        for dotted in keys:
            *parents, leaf = dotted.split(".")
            section = data
            for key in parents:
                section = section.get(key) if isinstance(section, dict) else None
            if isinstance(section, dict):
                section.pop(leaf, None)
        _save_config(path, data)


def write_telegram_allow_from(home: Path, slug: str, allow_from: str) -> None:
    """Записать allow_from в блок Telegram, который прочитает gateway; прочие списки доступа снять."""
    path = _profile_config_path(home, slug)
    with _config_write_lock(path):
        data = _load_config(path)
        blocks = [_dict_at(data, keys) for keys in _TELEGRAM_BLOCKS]
        effective = next((block for block in blocks if block is not None), None)
        if effective is None:
            effective = data.setdefault("platforms", {}).setdefault("telegram", {})
        for block in blocks:
            if block is not None:
                for key in _TELEGRAM_FOREIGN_KEYS:
                    block.pop(key, None)
        effective["allow_from"] = allow_from
        _save_config(path, data)


def _dict_at(data: dict, keys: tuple[str, ...]) -> dict | None:
    for key in keys:
        data = data.get(key) if isinstance(data, dict) else None
    return data if isinstance(data, dict) else None


def profile_port(home: Path, slug: str) -> int | None:
    if slug == DEFAULT_PROFILE:
        return int(os.environ.get("API_SERVER_PORT", DEFAULT_API_PORT))
    # Отклоняем всё, что не является плоским именем: traversal (..), слэши и т.д.
    if not SLUG_RE.fullmatch(slug):
        return None
    profile_dir = _profile_dir(home, slug)
    # .env приоритетнее config.yaml — соответствует get_env_value-логике hermes.
    return _env_port(profile_dir / ".env") or _config_yaml_port(profile_dir / "config.yaml")


def recoverable_profiles(home: Path) -> list[str]:
    """Слаги провиженных профилей, у которых назначен порт gateway'я.

    Используется при старте бриджа: только профили с портом были полноценно
    провиженны и нуждаются в gateway restart после рестарта контейнера.
    Профили без порта пропускаем — их gateway ещё не запускался.
    """
    profiles_dir = home / "profiles"
    if not profiles_dir.is_dir():
        # Каталога profiles/ нет — чистый старт, восстанавливать нечего.
        return []
    slugs = []
    for profile_dir in profiles_dir.iterdir():
        if not profile_dir.is_dir():
            continue
        slug = profile_dir.name
        # Невалидные слаги (traversal и пр.) profile_port отклонит сам.
        if profile_port(home, slug) is not None:
            slugs.append(slug)
    return sorted(slugs)


def pick_free_port(home: Path) -> int:
    used: set[int] = set()
    profiles = home / "profiles"
    if profiles.is_dir():
        for profile_dir in profiles.iterdir():
            if not profile_dir.is_dir():
                continue
            # Собираем занятые порты из обоих файлов каждого профиля.
            for port in (
                _env_port(profile_dir / ".env"),
                _config_yaml_port(profile_dir / "config.yaml"),
            ):
                if port is not None:
                    used.add(port)
    port = PROFILE_PORT_RANGE_START
    while port in used:
        port += 1
    return port


def timeout_for(path: str) -> float:
    return CHAT_TIMEOUT if path.rstrip("/").endswith("/chat") else DEFAULT_TIMEOUT


async def stream_forward(
    method: str, port: int, path: str, query: dict, body: bytes | None, api_key: str,
    upstream: str = "/api/sessions",
):
    """Стрим-форвард на api_server профиля: соединение открываем СРАЗУ (eager), чтобы
    ошибка подключения поднялась вызывающему (→ 502), а не утекла в уже начатый 200-поток.
    Клиент и ответ закрываем по исчерпании/обрыву генератора (finally).
    """
    url = f"http://127.0.0.1:{port}{upstream}{path}"
    headers = {"Authorization": f"Bearer {api_key}"}
    if body:
        headers["Content-Type"] = "application/json"
    client = httpx.AsyncClient(timeout=None)
    try:
        req = client.build_request(method, url, params=query, content=body, headers=headers)
        resp = await client.send(req, stream=True)
    except httpx.HTTPError:
        await client.aclose()
        raise
    # Upstream-ошибка (gateway вернул не-2xx) — это тоже agent_gateway_down, не льём её в SSE.
    if resp.status_code >= 400:
        await resp.aclose()
        await client.aclose()
        raise httpx.HTTPStatusError("upstream error", request=req, response=resp)

    async def gen():
        try:
            async for chunk in resp.aiter_bytes():
                yield chunk
        finally:
            await resp.aclose()
            await client.aclose()

    return gen()


async def forward(
    method: str, port: int, path: str, query: dict, body: bytes | None, api_key: str,
    upstream: str = "/api/sessions",
) -> tuple[int, object]:
    """Форвард на api_server профиля. Транспортные ошибки поднимаются httpx.HTTPError."""
    url = f"http://127.0.0.1:{port}{upstream}{path}"
    headers = {"Authorization": f"Bearer {api_key}"}
    if body:
        headers["Content-Type"] = "application/json"
    async with httpx.AsyncClient() as client:
        resp = await client.request(
            method, url, params=query, content=body, headers=headers, timeout=timeout_for(path),
        )
    if not resp.content:
        # Пустое тело (204 No Content и т.п.) — не пытаемся парсить JSON.
        payload = None
    else:
        try:
            payload = resp.json()
        except ValueError:
            payload = {"detail": resp.text}
    return resp.status_code, payload
