# retoor <retoor@molodetz.nl>

from typing import Annotated

from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse

from devplacepy.database import (
    db,
    get_table,
    get_users_by_uids,
    resolve_by_slug,
    search_users_by_username,
)
from devplacepy.models import ContainerAdminCreateForm, ContainerEditForm
from devplacepy.responses import action_result, json_error, respond
from devplacepy.schemas import (
    AdminContainerEditOut,
    AdminContainerInstanceOut,
    AdminContainersOut,
)
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.services.containers import api, store
from devplacepy.services.containers.api import ContainerError
from devplacepy.services.audit import record as audit
from devplacepy.utils import not_found, require_admin

router = APIRouter()

BOOT_LANGUAGES = list(api.BOOT_LANGUAGES)
RESTART_POLICIES = list(store.RESTART_POLICIES)


def _project_index(project_uids: set) -> dict:
    if not project_uids or "projects" not in db.tables:
        return {}
    table = get_table("projects")
    rows = table.find(table.table.columns.uid.in_(list(project_uids)))
    return {row["uid"]: row for row in rows}


def _decorate(instances: list) -> list:
    index = _project_index({inst["project_uid"] for inst in instances})
    decorated = []
    for inst in instances:
        project = index.get(inst["project_uid"], {})
        row = dict(inst)
        row["project_title"] = project.get("title", "")
        row["project_slug"] = project.get("slug") or project.get("uid") or ""
        decorated.append(row)
    decorated.sort(key=lambda r: r.get("created_at", ""), reverse=True)
    return decorated


def _instance_or_404(uid: str) -> dict:
    inst = store.get_instance(uid)
    if not inst:
        raise not_found("Instance not found")
    return inst


def _project_of(inst: dict) -> dict:
    return get_table("projects").find_one(uid=inst["project_uid"]) or {}


def _audit_admin(request: Request, admin: dict, event_key: str, inst: dict, summary: str, metadata=None) -> None:
    audit.record(
        request,
        event_key,
        user=admin,
        target_type="instance",
        target_uid=inst["uid"],
        target_label=inst.get("name"),
        metadata=metadata,
        summary=summary,
        links=[audit.instance(inst["uid"], inst.get("name"))],
    )


@router.get("", response_class=HTMLResponse)
async def containers_index(request: Request):
    admin = require_admin(request)
    instances = _decorate(store.all_instances())
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title="Containers - Admin",
        description="Manage container instances across all projects.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Containers", "url": "/admin/containers"},
        ],
        schemas=[website_schema(base)],
    )

    return respond(
        request,
        "containers_admin.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "instances": instances,
            "boot_languages": BOOT_LANGUAGES,
            "restart_policies": RESTART_POLICIES,
            "admin_section": "containers",
        },
        model=AdminContainersOut,
    )


@router.get("/data")
async def containers_index_json(request: Request):
    require_admin(request)
    return JSONResponse({"instances": _decorate(store.all_instances())})


@router.get("/projects/search")
async def project_search(request: Request, q: str = ""):
    require_admin(request)
    if not q or "projects" not in db.tables:
        return JSONResponse({"results": []})
    rows = db.query(
        "SELECT uid, slug, title FROM projects "
        "WHERE deleted_at IS NULL AND title LIKE :q LIMIT 10",
        q=f"%{q}%",
    )
    results = [
        {"uid": r["uid"], "slug": r["slug"] or r["uid"], "title": r["title"]}
        for r in rows
    ]
    return JSONResponse({"results": results})


@router.get("/users/search")
async def user_search(request: Request, q: str = ""):
    require_admin(request)
    if not q:
        return JSONResponse({"results": []})
    return JSONResponse({"results": search_users_by_username(q)})


@router.post("/create")
async def container_create(
    request: Request, data: Annotated[ContainerAdminCreateForm, Form()]
):
    admin = require_admin(request)
    project = resolve_by_slug(get_table("projects"), data.project_slug)
    if not project:
        return json_error(404, "project not found")
    try:
        inst = await api.create_instance(
            project,
            name=data.name,
            boot_command=data.boot_command,
            boot_language=data.boot_language,
            boot_script=data.boot_script,
            run_as_uid=data.run_as_uid,
            start_on_boot=data.start_on_boot,
            env=data.env,
            cpu_limit=data.cpu_limit,
            mem_limit=data.mem_limit,
            ports=data.ports,
            volumes=data.volumes,
            restart_policy=data.restart_policy,
            autostart=data.autostart,
            ingress_slug=data.ingress_slug,
            ingress_port=data.ingress_port,
            actor=("user", admin["uid"]),
        )
    except ContainerError as exc:
        return json_error(400, str(exc))
    _audit_admin(
        request,
        admin,
        "container.instance.create",
        inst,
        f"admin {admin['username']} created container instance {inst.get('name')}",
        metadata={
            "project": project.get("title"),
            "boot_language": data.boot_language,
            "run_as_uid": data.run_as_uid or None,
            "start_on_boot": data.start_on_boot,
        },
    )
    return action_result(request, "/admin/containers", data={"instance": inst})


@router.get("/{uid}/edit", response_class=HTMLResponse)
async def container_edit_page(request: Request, uid: str):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    project = _project_of(inst)
    run_as_user = None
    if inst.get("run_as_uid"):
        run_as_user = get_users_by_uids([inst["run_as_uid"]]).get(inst["run_as_uid"])
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title=f"Edit {inst['name']} - Containers",
        description=f"Edit container instance {inst['name']}.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Containers", "url": "/admin/containers"},
            {"name": inst["name"], "url": f"/admin/containers/{inst['uid']}"},
            {"name": "Edit", "url": f"/admin/containers/{inst['uid']}/edit"},
        ],
        schemas=[website_schema(base)],
    )
    return respond(
        request,
        "containers_edit.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "instance": inst,
            "project": project,
            "run_as_user": run_as_user,
            "boot_languages": BOOT_LANGUAGES,
            "restart_policies": RESTART_POLICIES,
            "admin_section": "containers",
        },
        model=AdminContainerEditOut,
    )


@router.post("/{uid}/edit")
async def container_edit(
    request: Request, uid: str, data: Annotated[ContainerEditForm, Form()]
):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    try:
        updated = api.update_instance_config(
            inst,
            run_as_uid=data.run_as_uid,
            boot_language=data.boot_language,
            boot_script=data.boot_script,
            boot_command=data.boot_command,
            restart_policy=data.restart_policy,
            start_on_boot=data.start_on_boot,
            cpu_limit=data.cpu_limit,
            mem_limit=data.mem_limit,
            actor=("user", admin["uid"]),
        )
    except ContainerError as exc:
        return json_error(400, str(exc))
    _audit_admin(
        request,
        admin,
        "container.instance.configure",
        updated,
        f"admin {admin['username']} edited container instance {updated.get('name')}",
        metadata={
            "boot_language": data.boot_language,
            "run_as_uid": data.run_as_uid or None,
            "start_on_boot": data.start_on_boot,
            "restart_policy": data.restart_policy,
        },
    )
    return action_result(
        request, f"/admin/containers/{uid}", data={"instance": updated}
    )


_ACTIONS = {
    "start": store.DESIRED_RUNNING,
    "stop": store.DESIRED_STOPPED,
    "pause": store.DESIRED_PAUSED,
    "resume": store.DESIRED_RUNNING,
}


@router.post("/{uid}/start")
@router.post("/{uid}/stop")
@router.post("/{uid}/pause")
@router.post("/{uid}/resume")
@router.post("/{uid}/restart")
async def container_action(request: Request, uid: str):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    actor = ("user", admin["uid"])
    action = request.url.path.rsplit("/", 1)[-1]
    if action == "restart":
        api.request_restart(inst, actor=actor)
    else:
        api.set_desired_state(inst, _ACTIONS[action], actor=actor)
    _audit_admin(
        request,
        admin,
        f"container.instance.{action}",
        inst,
        f"admin {admin['username']} {action} container instance {inst.get('name')}",
    )
    return action_result(
        request, "/admin/containers", data={"uid": uid, "action": action}
    )


@router.post("/{uid}/sync")
async def container_sync(request: Request, uid: str):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    try:
        counts = await api.sync_workspace(inst, admin)
    except ContainerError as exc:
        return json_error(400, str(exc))
    _audit_admin(
        request,
        admin,
        "container.instance.sync",
        inst,
        f"admin {admin['username']} synced the workspace of instance {inst.get('name')}",
        metadata=counts,
    )
    return action_result(request, f"/admin/containers/{uid}", data=counts)


@router.post("/{uid}/delete")
async def container_delete(request: Request, uid: str):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    api.mark_for_removal(inst, actor=("user", admin["uid"]))
    _audit_admin(
        request,
        admin,
        "container.instance.delete",
        inst,
        f"admin {admin['username']} removed container instance {inst.get('name')}",
    )
    return action_result(request, "/admin/containers", data={"uid": uid})


@router.get("/{uid}", response_class=HTMLResponse)
async def container_instance_page(request: Request, uid: str):
    admin = require_admin(request)
    inst = _instance_or_404(uid)
    project = _project_of(inst)
    project_slug = project.get("slug") or project.get("uid") or ""
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title=f"{inst['name']} - Containers",
        description=f"Container instance {inst['name']}.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Containers", "url": "/admin/containers"},
            {"name": inst["name"], "url": f"/admin/containers/{inst['uid']}"},
        ],
        schemas=[website_schema(base)],
    )

    return respond(
        request,
        "containers_instance.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "instance": inst,
            "project": project,
            "project_slug": project_slug,
            "events": store.list_events(inst["uid"]),
            "schedules": store.list_schedules(inst["uid"]),
            "stats": api.instance_stats(inst["uid"]),
            "runtime": api.instance_runtime(inst),
            "admin_section": "containers",
        },
        model=AdminContainerInstanceOut,
    )
