"""Match API endpoints"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from app.core.db.database import get_db
from app.core.db.repositories.match_repository import MatchRepository
from app.core.db.repositories.league_repository import LeagueRepository
from pydantic import BaseModel

router = APIRouter()

class MatchResponse(BaseModel):
    id: int
    league_id: int
    league_name: str
    home_team_name: str
    away_team_name: str
    match_date: datetime
    status: str
    home_score: Optional[int]
    away_score: Optional[int]
    class Config:
        from_attributes = True

@router.get("/matches/upcoming")
async def get_upcoming_matches(
    league: Optional[str] = Query(None, description="League ID"),
    from_date: Optional[datetime] = Query(None, description="From date"),
    to_date: Optional[datetime] = Query(None, description="To date"),
    limit: int = Query(100, ge=1, le=1000),
    db: Session = Depends(get_db)
):
    league_id = None
    if league and league.strip():
        try:
            league_id = int(league)
        except (ValueError, TypeError):
            league_id = None
    
    match_repo = MatchRepository(db)
    league_repo = LeagueRepository(db)
    
    matches = match_repo.get_upcoming(
        league_id=league_id,
        from_date=from_date,
        to_date=to_date,
        limit=limit
    )
    
    result = []
    for match in matches:
        league_obj = league_repo.get_by_id(match.league_id)
        result.append(MatchResponse(
            id=match.id,
            league_id=match.league_id,
            league_name=league_obj.name if league_obj else "Unknown",
            home_team_name=match.home_team.name,
            away_team_name=match.away_team.name,
            match_date=match.match_date,
            status=match.status,
            home_score=match.home_score,
            away_score=match.away_score
        ))
    
    return result
