from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
from app.feedback.feedback_collector import get_feedback_collector

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

class FeedbackRequest(BaseModel):
    query: str
    response: str
    rating: int = Field(ge=1, le=5, description="Rating from 1 (bad) to 5 (excellent)")
    correction: Optional[str] = None
    persona: str = "Eden"
    metadata: Optional[dict] = None

class TrainingStats(BaseModel):
    ready_to_train: bool
    examples_needed: int
    current_examples: int
    stats: dict

@router.post("/submit")
async def submit_feedback(feedback: FeedbackRequest):
    """Submit feedback on Eden's response"""
    collector = get_feedback_collector()
    result = collector.collect_feedback(
        query=feedback.query,
        response=feedback.response,
        rating=feedback.rating,
        correction=feedback.correction,
        persona=feedback.persona,
        metadata=feedback.metadata
    )
    return result

@router.get("/stats")
async def get_feedback_stats():
    """Get feedback collection statistics"""
    collector = get_feedback_collector()
    stats = collector.get_stats()
    
    # Check if ready to fine-tune (need 1000+ examples)
    total = stats['total']
    ready = total >= 1000
    
    return TrainingStats(
        ready_to_train=ready,
        examples_needed=max(0, 1000 - total),
        current_examples=total,
        stats=stats
    )

@router.post("/trigger-training")
async def trigger_training():
    """Trigger fine-tuning when enough examples collected"""
    collector = get_feedback_collector()
    total = collector.count_examples()
    
    if total < 1000:
        raise HTTPException(
            status_code=400,
            detail=f"Need at least 1000 examples. Currently have {total}."
        )
    
    # TODO: Implement actual fine-tuning
    return {
        "status": "training_queued",
        "message": "Fine-tuning will be implemented in Phase 2",
        "examples": total
    }
