"""Аутентифицированная консольная граница нативного OAuth профиля."""

from contextlib import contextmanager
from pathlib import Path
from typing import Literal

from fastapi import APIRouter, HTTPException

from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, field_validator

from app import proxy

router = APIRouter(prefix="/agents/{slug}/mcp")


class IdentityConfig(BaseModel):
    tool: str = Field(min_length=1, max_length=128)
    idField: str = Field(min_length=1, max_length=256)
    nameField: str | None = Field(default=None, min_length=1, max_length=256)
    idFormat: Literal["positive_integer", "string"]

    @field_validator("idField", "nameField")
    @classmethod
    def property_path(cls, path: str | None) -> str | None:
        import re

        if path is not None and any(
            not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", segment)
            or segment in {"__proto__", "prototype", "constructor"}
            for segment in path.split(".")
        ):
            raise ValueError("invalid_identity_path")
        return path


class OAuthConfig(BaseModel):
    model_config = ConfigDict(extra="allow")
    identity: IdentityConfig | None = None


class McpConfig(BaseModel):
    model_config = ConfigDict(extra="allow")
    url: AnyHttpUrl
    auth: Literal["oauth"]
    oauth: OAuthConfig = Field(default_factory=OAuthConfig)


class StartBody(BaseModel):
    redirectUri: str = Field(min_length=1, max_length=2048)
    config: McpConfig


class CallbackBody(BaseModel):
    state: str = Field(min_length=1, max_length=2048)
    code: str | None = Field(default=None, max_length=8192)
    error: str | None = Field(default=None, max_length=256)


class CommitBody(BaseModel):
    revision: str = Field(min_length=1, max_length=128)


def _owner():
    from plugins.agentek_runtime import mcp_connections
    from plugins.agentek_runtime.patches import mcp_oauth

    mcp_oauth.apply()
    return mcp_connections


def _home(slug: str) -> Path:
    path = proxy._profile_config_path(proxy.hermes_home(), slug)
    if not path.exists():
        raise HTTPException(404, detail={"error": "agent_not_found"})
    return path.parent


@contextmanager
def _errors():
    owner = _owner()
    try:
        yield owner
    except owner.ConnectionError as err:
        raise HTTPException(err.status, detail={"error": err.code}) from err
    except (TimeoutError, OSError, RuntimeError) as err:
        raise HTTPException(503, detail={"error": "unavailable"}) from err
    except (KeyError, ValueError) as err:
        raise HTTPException(400, detail={"error": "invalid_request"}) from err


@router.post("/{name}/oauth/start")
def start(slug: str, name: str, body: StartBody) -> dict:
    with _errors() as owner:
        return owner.start(
            _home(slug), name, body.model_dump(mode="json", exclude_none=True)
        )


@router.post("/oauth/invalidate")
def invalidate_all(slug: str) -> dict:
    with _errors() as owner:
        return owner.invalidate_all(_home(slug))


@router.post("/{name}/oauth/invalidate")
def invalidate(slug: str, name: str) -> dict:
    with _errors() as owner:
        return owner.invalidate(_home(slug), name)


@router.get("/{name}/oauth/{flow_id}")
def poll(slug: str, name: str, flow_id: str) -> dict:
    with _errors() as owner:
        return owner.poll(_home(slug), name, flow_id)


@router.post("/{name}/oauth/{flow_id}/callback")
def callback(slug: str, name: str, flow_id: str, body: CallbackBody) -> dict:
    with _errors() as owner:
        return owner.callback(_home(slug), name, flow_id, body.model_dump())


@router.delete("/{name}/oauth/{flow_id}")
def cancel(slug: str, name: str, flow_id: str) -> dict:
    with _errors() as owner:
        return owner.cancel(_home(slug), name, flow_id)


@router.post("/{name}/oauth/{flow_id}/commit")
def commit(slug: str, name: str, flow_id: str, body: CommitBody) -> dict:
    with _errors() as owner:
        return owner.commit(_home(slug), name, flow_id, body.revision)


@router.get("/{name}/connection")
def connection(slug: str, name: str) -> dict:
    with _errors() as owner:
        return owner.connection(_home(slug), name)


def validate_public_name(name: str) -> None:
    from plugins.agentek_runtime import mcp_connections

    try:
        mcp_connections.validate_public_name(name)
    except mcp_connections.ConnectionError as err:
        raise HTTPException(err.status, detail={"error": err.code}) from err


def managed(slug: str, name: str) -> bool:
    from plugins.agentek_runtime import mcp_connections

    return mcp_connections.managed(
        proxy._profile_config_path(proxy.hermes_home(), slug).parent, name
    )


def set_enabled(slug: str, name: str, enabled: bool) -> dict:
    with _errors() as owner:
        return (
            owner.enable(_home(slug), name)
            if enabled
            else owner.disable(_home(slug), name)
        )


def delete(slug: str, name: str) -> dict:
    with _errors() as owner:
        return owner.delete(_home(slug), name)


def enrich(slug: str, entries: list[dict]) -> list[dict]:
    if not entries:
        return entries
    from plugins.agentek_runtime import mcp_connections

    home = _home(slug)
    for entry in entries:
        if mcp_connections.managed(home, entry["name"]):
            connection = mcp_connections.connection(home, entry["name"])
            entry["oauth"] = {
                "authRequired": connection["authStatus"] == "auth_required",
                "unavailable": connection["authStatus"] == "unavailable",
            }
            if connection.get("account"):
                entry["oauth"]["account"] = connection["account"]
    return entries
