"""
OCR API Routes
"""
from fastapi import APIRouter, HTTPException, UploadFile, File, Query
from typing import List, Optional

from app.services.ocr_service import ocr_service

router = APIRouter()


@router.post("/extract", summary="Extract text from image")
async def extract_text(
    file: UploadFile = File(...),
    languages: str = Query("en", description="Comma-separated language codes"),
    preprocess: bool = Query(True, description="Apply image preprocessing")
):
    """
    Extract text from an uploaded image
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    contents = await file.read()
    lang_list = [l.strip() for l in languages.split(",")]

    result = await ocr_service.extract_text(contents, lang_list, preprocess)

    return {
        "filename": file.filename,
        **result
    }


@router.post("/extract/structured", summary="Extract structured data")
async def extract_structured(
    file: UploadFile = File(...),
    document_type: str = Query("general", description="Document type: invoice, receipt, id_card, general")
):
    """
    Extract structured data from a document image
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    contents = await file.read()
    result = await ocr_service.extract_structured_data(contents, document_type)

    return {
        "filename": file.filename,
        **result
    }


@router.post("/batch", summary="Batch OCR processing")
async def batch_extract(
    files: List[UploadFile] = File(...),
    languages: str = Query("en", description="Comma-separated language codes")
):
    """
    Extract text from multiple images
    """
    if len(files) > 10:
        raise HTTPException(status_code=400, detail="Maximum 10 files per batch")

    lang_list = [l.strip() for l in languages.split(",")]
    results = []

    for file in files:
        if not file.content_type.startswith("image/"):
            results.append({
                "filename": file.filename,
                "error": "Not an image file"
            })
            continue

        contents = await file.read()
        result = await ocr_service.extract_text(contents, lang_list)
        results.append({
            "filename": file.filename,
            **result
        })

    return {
        "total_files": len(files),
        "results": results
    }


@router.get("/languages", summary="Get supported languages")
async def get_languages():
    """
    Get list of supported OCR languages
    """
    return {
        "supported_languages": [
            {"code": "en", "name": "English"},
            {"code": "hi", "name": "Hindi"},
            {"code": "ta", "name": "Tamil"},
            {"code": "te", "name": "Telugu"},
            {"code": "kn", "name": "Kannada"},
            {"code": "ml", "name": "Malayalam"},
            {"code": "mr", "name": "Marathi"},
            {"code": "bn", "name": "Bengali"},
            {"code": "gu", "name": "Gujarati"},
            {"code": "pa", "name": "Punjabi"}
        ]
    }
