from sqlalchemy.orm import Session
from fastapi import HTTPException
from typing import Dict, Any, List, Optional
from datetime import datetime
import logging
from src.apps.match.enums import MatchedType
from src.apps.wine_match.job.wine_match_job import trigger_wine_match_job

logger = logging.getLogger(__name__)

async def process_wine_match(db: Session, params: Dict[str, Any]) -> Dict[str, Any]:
    """
    Direct conversion of the Groovy proceed() method to Python.
    
    Args:
        db: Database session
        params: Request parameters including retailers and matchedType
        
    Returns:
        Dict: Result of operation
    """
    # Initialize variables similar to Groovy implementation
    codes = []
    run_keywords = []
    dates = []
    
    # Parse matched type - directly from the Groovy code
    matched_type = params.get("matchedType", "")
    run_keyword = MatchedType.KEYWORD.value.lower() == matched_type.lower()
    
    # Process retailers data - equivalent to the Groovy loop
    retailers = params.get("retailers", {})
    if retailers:
        for k, v in retailers.items():
            if "." in k:
                continue
                
            if v and "code" in v:
                codes.append(v["code"])
                run_keywords.append(run_keyword)
                
                # Parse date
                date = None
                date_string = v.get("date")
                if date_string:
                    try:
                        date = datetime.strptime(date_string, "%Y-%m-%d")
                    except Exception as e:
                        logger.error(f"Error parsing date: {str(e)}")
                
                dates.append(date)
    
    # Validate files - check for errors like in the Groovy version
    errors = []
    for i, code in enumerate(codes):
        d = dates[i] if i < len(dates) else None
        if d:
            # This would typically call your output service to validate the file
            # For now, we'll assume all files are valid
            valid_file = True
            if not valid_file:
                errors.append(f"Input file not found for [{code}] at date [{d.strftime('%Y-%m-%d')}]")
        else:
            errors.append(f"Input file not found for [{code}] at date [null]")
    
    # If there are errors, raise an exception
    if errors:
        raise HTTPException(status_code=400, detail=errors)
    
    # Trigger the job (equivalent to WineMatchJob.triggerNow in Groovy)
    await trigger_wine_match_job(
        db=db,
        codes=codes,
        run_keywords=run_keywords,
        dates=dates,
        mode=params.get("mode")
    )
    result = {
        "status": "scheduled", 
        "codes": codes,
        "run_keywords": run_keywords,
        "dates": [d.strftime("%Y-%m-%d") if d else None for d in dates],
        "mode": params.get("mode")
    }
    return result
