"""Admin API endpoints"""
from fastapi import APIRouter, Depends, HTTPException, Header
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import Optional
from app.core.db.database import get_db
from app.core.config import settings
from app.agents.data_ingest_agent import DataIngestAgent
from app.agents.feature_agent import FeatureAgent
from app.agents.training_agent import TrainingAgent
from app.agents.prediction_agent import PredictionAgent
from app.agents.backtest_agent import BacktestAgent
from app.agents.quality_agent import QualityAgent
from app.agents.llm_analysis_agent import LLMAnalysisAgent

router = APIRouter()


def verify_api_key(x_api_key: Optional[str] = Header(None)):
    """Verify API key"""
    if not x_api_key or x_api_key != settings.api_key:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return x_api_key


class AgentRunRequest(BaseModel):
    agent_name: str


@router.post("/run-agent")
async def run_agent(
    request: AgentRunRequest,
    db: Session = Depends(get_db),
    api_key: str = Depends(verify_api_key)
):
    """Run an agent manually"""
    agent_map = {
        "DataIngestAgent": DataIngestAgent,
        "FeatureAgent": FeatureAgent,
        "TrainingAgent": TrainingAgent,
        "PredictionAgent": PredictionAgent,
        "BacktestAgent": BacktestAgent,
        "QualityAgent": QualityAgent,
    }
    
    if request.agent_name not in agent_map:
        raise HTTPException(
            status_code=400,
            detail=f"Unknown agent: {request.agent_name}. Available: {list(agent_map.keys())}"
        )
    
    agent_class = agent_map[request.agent_name]
    agent = agent_class(db)
    
    success = agent.run()
    
    return {
        "agent": request.agent_name,
        "success": success,
        "run_id": agent.current_run
    }


@router.post("/pipeline")
async def run_pipeline(
    db: Session = Depends(get_db),
    api_key: str = Depends(verify_api_key)
):
    """Run full pipeline: ingest -> features -> train -> predict"""
    results = {}
    
    # Ingest
    ingest_agent = DataIngestAgent(db)
    results["ingest"] = ingest_agent.run()
    
    # Features
    feature_agent = FeatureAgent(db)
    results["features"] = feature_agent.run()
    
    # Training (if enabled)
    if settings.training_enabled:
        training_agent = TrainingAgent(db)
        results["training"] = training_agent.run()
    
    # Predict
    prediction_agent = PredictionAgent(db)
    results["predict"] = prediction_agent.run()

    # LLM analysis (optional)
    if settings.llm_analysis_enabled and settings.openai_api_key:
        llm_agent = LLMAnalysisAgent(db)
        results["llm_analysis"] = llm_agent.run()
    
    return {
        "success": all(results.values()),
        "results": results
    }

