"""Jobs router — list templates and run jobs."""

from __future__ import annotations

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from media_library_viewer_api.clients.ssh import RemoteSSHClient
from media_library_viewer_api.dependencies import get_ssh_client
from media_library_viewer_api.jobs import JOB_TEMPLATES, run_job

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/jobs", tags=["jobs"])


class RunJobRequest(BaseModel):
    job_key: str
    path: str


@router.get("/templates")
def get_templates() -> list[dict[str, str]]:
    """Return available job templates."""
    templates = [
        {
            "key": key,
            "name": template.name,
            "description": template.description,
        }
        for key, template in JOB_TEMPLATES.items()
    ]
    logger.info("Jobs templates requested count=%s", len(templates))
    return templates


@router.post("/run")
def post_run_job(
    request: RunJobRequest,
    ssh: RemoteSSHClient = Depends(get_ssh_client),
) -> dict[str, Any]:
    """Run a job template on a remote path."""
    if request.job_key not in JOB_TEMPLATES:
        logger.warning("Unknown job requested key=%s path=%s", request.job_key, request.path)
        raise HTTPException(status_code=400, detail=f"Unknown job key: {request.job_key}")

    logger.info("Running job key=%s path=%s", request.job_key, request.path)
    result = run_job(ssh, request.job_key, request.path)
    logger.info("Job finished key=%s exit_status=%s path=%s", request.job_key, result.exit_status, request.path)
    return {
        "job_key": request.job_key,
        "path": request.path,
        "exit_status": result.exit_status,
        "stdout": result.stdout,
        "stderr": result.stderr,
    }
