import base64
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from backend.ocr_engine import get_ocr_reader, run_ocr_on_image
from backend.parser import extract_cccd_info
import time

app = FastAPI(
    title="Vietnamese Card OCR API",
    description="API for reading and parsing information from Vietnamese Citizen Identity Cards (CCCD)",
    version="1.0.0"
)

# Enable CORS for all domains so widget embedding works seamlessly
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup_event():
    """Warm up the OCR model on app startup to reduce latency on first request."""
    print("FastAPI application starting up...")
    try:
        get_ocr_reader()
        print("Warmup complete. Application is ready to accept requests.")
    except Exception as e:
        print(f"Error during model warmup: {e}")

@app.get("/")
def read_root():
    return {
        "status": "online",
        "message": "Vietnamese Identity Card OCR API is running. Send POST requests to /api/ocr/cccd",
        "docs": "/docs"
    }

@app.post("/api/ocr/cccd")
async def ocr_cccd(file: UploadFile = File(...)):
    # Validate file type
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Uploaded file must be an image.")
        
    start_time = time.time()
    
    try:
        # 1. Read bytes from uploaded file
        contents = await file.read()
        
        # 2. Run OCR using EasyOCR & preprocessing
        raw_results, processed_img_bytes, is_warped = run_ocr_on_image(contents)
        
        # 3. Parse fields using regex rules
        parsed_info = extract_cccd_info(raw_results)
        
        # 4. Convert processed image to base64 for frontend visual confirmation
        base64_img = base64.b64encode(processed_img_bytes).decode('utf-8')
        img_data_uri = f"data:image/jpeg;base64,{base64_img}"
        
        processing_time = time.time() - start_time
        print(f"Request processed in {processing_time:.2f} seconds.")
        
        return {
            "success": True,
            "processing_time_sec": round(processing_time, 2),
            "is_warped": is_warped,
            "data": parsed_info,
            "processed_image": img_data_uri
        }
        
    except ValueError as val_err:
        raise HTTPException(status_code=400, detail=str(val_err))
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
