"""Unified execution records API (scripts + server batch jobs)."""

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query

from server.api.auth_jwt import get_current_admin
from server.api.dependencies import get_script_service
from server.application.services.execution_record_service import (
    get_execution_record_detail,
    list_execution_records,
)
from server.application.services.script_service import ScriptService
from server.domain.models import Admin

router = APIRouter(prefix="/api/execution-records", tags=["execution-records"])


@router.get("", response_model=dict)
async def list_records(
    limit: int = Query(50, ge=1, le=200),
    offset: int = Query(0, ge=0),
    status: Optional[str] = Query(None, description="running/completed/failed/partial/cancelled"),
    kind: Optional[str] = Query(None, description="script | server_batch"),
    admin: Admin = Depends(get_current_admin),
    script_service: ScriptService = Depends(get_script_service),
):
    """List script executions and server batch jobs merged, newest first."""
    if kind and kind not in ("script", "server_batch"):
        raise HTTPException(status_code=400, detail="kind 须为 script 或 server_batch")
    return await list_execution_records(
        script_service=script_service,
        limit=limit,
        offset=offset,
        status=status,
        kind=kind,
    )


@router.get("/{record_id}", response_model=dict)
async def get_record_detail(
    record_id: int,
    kind: str = Query(..., description="script | server_batch"),
    fetch_logs: bool = Query(False),
    admin: Admin = Depends(get_current_admin),
    script_service: ScriptService = Depends(get_script_service),
):
    """Execution detail for script run or server batch job."""
    if kind not in ("script", "server_batch"):
        raise HTTPException(status_code=400, detail="kind 须为 script 或 server_batch")
    detail = await get_execution_record_detail(
        script_service=script_service,
        record_id=record_id,
        kind=kind,
        fetch_logs=fetch_logs,
    )
    if not detail:
        raise HTTPException(status_code=404, detail="执行记录不存在")
    return detail
