from fastapi import APIRouter, HTTPException, Query

from app.schemas.monitor import CreateExperimentRequest
from app.services.monitor_service import MonitorService
from app.utils.response import success_response

router = APIRouter()
service = MonitorService()


# ── 元数据接口 ────────────────────────────────────────────────────────────────

@router.get('/models')
def list_models():
    return success_response(data=service.list_models())


@router.get('/packages')
def list_packages():
    return success_response(data=service.list_packages())


# ── 试验 CRUD ─────────────────────────────────────────────────────────────────

@router.get('/experiments')
def list_experiments():
    return success_response(data=service.list_experiments())


@router.post('/experiments')
def create_experiment(req: CreateExperimentRequest):
    try:
        exp = service.create_experiment(
            name=req.name.strip(),
            model_id=req.model_id,
            input_csv_path=req.input_csv_path.strip(),
            output_csv_path=req.output_csv_path.strip(),
            target_temp=req.target_temp,
            sampling_interval=req.sampling_interval,
            mpc_params=req.mpc_params.model_dump(),
        )
        return success_response(data=exp, message='试验创建成功')
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.get('/experiments/{exp_id}')
def get_experiment(exp_id: int):
    try:
        return success_response(data=service.get_experiment(exp_id))
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@router.delete('/experiments/{exp_id}')
def delete_experiment(exp_id: int):
    try:
        service.delete_experiment(exp_id)
        return success_response(message='试验已删除')
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


# ── 控制操作 ──────────────────────────────────────────────────────────────────

@router.post('/experiments/{exp_id}/start')
def start_experiment(exp_id: int):
    try:
        service.start_experiment(exp_id)
        return success_response(message='试验已启动')
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post('/experiments/{exp_id}/stop')
def stop_experiment(exp_id: int):
    try:
        service.stop_experiment(exp_id)
        return success_response(message='试验已停止')
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


# ── 数据 / 报告 / 导出 ────────────────────────────────────────────────────────

@router.get('/experiments/{exp_id}/data')
def get_data_points(exp_id: int, from_step: int = Query(default=0, ge=0)):
    return success_response(data=service.get_data_points(exp_id, from_step))




