"""Container listing, logs, and management."""

from fastapi import APIRouter, Query, HTTPException

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from lib_bridge import (
    portainer_list_containers,
    portainer_get_container_logs,
    portainer_restart_container,
    ENDPOINTS,
)

router = APIRouter(tags=["containers"])


@router.get("/containers")
def list_containers(endpoint: str | None = None):
    """List all containers across endpoints, optional endpoint filter."""
    targets = [endpoint] if endpoint and endpoint in ENDPOINTS else list(ENDPOINTS)
    results = []
    for ep in targets:
        try:
            containers = portainer_list_containers(ep)
            for c in containers:
                names = c.get("Names", [])
                name = names[0].lstrip("/") if names else c.get("Id", "")[:12]
                results.append({
                    "id": c.get("Id", "")[:12],
                    "name": name,
                    "image": c.get("Image", ""),
                    "state": c.get("State", ""),
                    "status": c.get("Status", ""),
                    "endpoint": ep,
                })
        except Exception as e:
            results.append({"endpoint": ep, "error": str(e)})
    return results


@router.get("/containers/{container_id}/logs")
def container_logs(container_id: str, endpoint: str = Query(...)):
    """Get container logs. Requires endpoint query param."""
    if endpoint not in ENDPOINTS:
        raise HTTPException(400, f"Unknown endpoint: {endpoint}")
    try:
        logs = portainer_get_container_logs(endpoint, container_id)
        return {"container_id": container_id, "endpoint": endpoint, "logs": logs}
    except Exception as e:
        raise HTTPException(502, f"Failed to get logs: {e}")


@router.post("/containers/{container_id}/restart")
def restart_container(container_id: str, endpoint: str = Query(...)):
    """Restart a container. Requires endpoint query param."""
    if endpoint not in ENDPOINTS:
        raise HTTPException(400, f"Unknown endpoint: {endpoint}")
    success = portainer_restart_container(endpoint, container_id)
    if not success:
        raise HTTPException(502, "Restart failed")
    return {"status": "restarted", "container_id": container_id, "endpoint": endpoint}
