from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Form
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.services.service_manager import ServiceManager
import csv
import io

router = APIRouter(prefix="/manabox")

service_manager = ServiceManager()

REQUIRED_HEADERS = {
    'Name', 'Set code', 'Set name', 'Collector number', 'Foil', 'Rarity',
    'Quantity', 'ManaBox ID', 'Scryfall ID', 'Purchase price', 'Misprint',
    'Altered', 'Condition', 'Language', 'Purchase price currency'
}

def is_valid_csv(file: UploadFile) -> tuple[bool, str]:
    # Check if filename ends with .csv
    if not file.filename.lower().endswith('.csv'):
        return False, "File must have a .csv extension"
    
    try:
        # Try to read the content as CSV
        content = file.file.read()
        # Reset file pointer for later use
        file.file.seek(0)
        
        # Try to parse the content as CSV
        csv_reader = csv.reader(io.StringIO(content.decode('utf-8')))
        
        # Get headers from first row
        headers = set(next(csv_reader))
        
        # Check for missing headers
        missing_headers = REQUIRED_HEADERS - headers
        if missing_headers:
            return False, f"Missing required columns: {', '.join(missing_headers)}"
        
        # Check for extra headers
        extra_headers = headers - REQUIRED_HEADERS
        if extra_headers:
            return False, f"Unexpected columns found: {', '.join(extra_headers)}"
            
        return True, "Valid CSV format"
    except (csv.Error, UnicodeDecodeError) as e:
        return False, f"Invalid CSV format: {str(e)}"
    except StopIteration:
        return False, "Empty file"

@router.post("/process-csv")
async def process_manabox_csv(
    file: UploadFile = File(...),
    source: str = Form(...),
    description: str = Form(...),
    db: Session = Depends(get_db)
):  
    try:
        is_valid, error_message = is_valid_csv(file)
        if not is_valid:
            raise HTTPException(
                status_code=400, 
                detail=error_message
            )

        content = await file.read()

        metadata = {
            "source": source,
            "description": description
        }

        manabox_service = service_manager.get_service("manabox")

        success = await manabox_service.process_manabox_csv(db, content, metadata)
        
        if not success:
            raise HTTPException(status_code=400, detail="Failed to process CSV file")
        
        return {"message": "CSV processed successfully"}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/manabox-file-uploads")
async def get_manabox_file_uploads(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    file_service = service_manager.get_service("file")
    files = await file_service.list_files(db, skip=skip, limit=limit, file_type="manabox")
    return files