import json
from typing import Any, List
from fastapi import APIRouter, Depends, UploadFile, File, Form, HTTPException, Query
from sqlalchemy.orm import Session
from app.api.v1.deps import get_db, get_current_active_user
from app.models.user import User
from app.schemas.import_log import ImportPreview, ImportLog as ImportLogSchema, ImportMapping
from app.services.import_service import UserImportService
from app.models.import_log import ImportLog

router = APIRouter()

@router.post("/import/preview", response_model=ImportPreview)
async def preview_import_file(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_active_user),
):
    """
    Upload file and preview first few rows to help with mapping.
    """
    if not file.filename.endswith(('.xlsx', '.xls', '.csv')):
        raise HTTPException(status_code=400, detail="Invalid file format")
    
    contents = await file.read()
    try:
        result = UserImportService.preview_excel(contents, file.filename)
        # Create default headers (A, B, C...) if needed, but the service returns data list
        data = result["preview_data"]
        headers = []
        if data and len(data) > 0:
            # Assuming max columns based on first row
            num_cols = len(data[0])
            # Generate A, B, C...
            import string
            headers = [string.ascii_uppercase[i] for i in range(min(num_cols, 26))] 
            # If more than 26, it gets complex (AA, AB), simple loop:
            # For now assume < 26 columns or frontend handles it
        
        return {
            "headers": headers, 
            "preview_data": data
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/import", response_model=ImportLogSchema)
async def import_users(
    file: UploadFile = File(...),
    start_row: int = Form(...),
    mapping: str = Form(...), # JSON string
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
):
    """
    Execute import with file and mapping configuration.
    Mapping example: {"mobile": 0, "name": 1}
    """
    try:
        mapping_dict = json.loads(mapping)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid mapping JSON")
        
    contents = await file.read()
    try:
        log = UserImportService.process_import(
            db=db,
            file_contents=contents,
            filename=file.filename,
            start_row=start_row,
            mapping=mapping_dict,
            user_id=current_user.id
        )
        return log
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/import/logs", response_model=List[ImportLogSchema])
def get_import_logs(
    skip: int = 0,
    limit: int = 10,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
):
    logs = db.query(ImportLog).order_by(ImportLog.created_at.desc()).offset(skip).limit(limit).all()
    return logs

@router.get("/import/logs/{log_id}", response_model=ImportLogSchema)
def get_import_log(
    log_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
):
    log = db.query(ImportLog).filter(ImportLog.id == log_id).first()
    if not log:
        raise HTTPException(status_code=404, detail="Log not found")
    return log

