"""Agent run API endpoints"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.core.db.database import get_db
from app.core.db.repositories.agent_run_repository import AgentRunRepository
from pydantic import BaseModel
from datetime import datetime

router = APIRouter()


class RunResponse(BaseModel):
    id: int
    agent_name: str
    status: str
    started_at: datetime
    finished_at: Optional[datetime]
    error: Optional[str]
    matches_processed: int
    records_created: int
    records_updated: int
    
    class Config:
        from_attributes = True


@router.get("/runs")
async def get_runs(
    agent_name: Optional[str] = Query(None, description="Filter by agent name"),
    limit: int = Query(50, ge=1, le=500),
    db: Session = Depends(get_db)
):
    """Get agent run history"""
    run_repo = AgentRunRepository(db)
    runs = run_repo.get_recent(agent_name=agent_name, limit=limit)
    
    return [RunResponse(
        id=r.id,
        agent_name=r.agent_name,
        status=r.status,
        started_at=r.started_at,
        finished_at=r.finished_at,
        error=r.error,
        matches_processed=r.matches_processed,
        records_created=r.records_created,
        records_updated=r.records_updated
    ) for r in runs]

