"""
FastAPI Server for Property Image Verification System

This server provides endpoints for:
1. Uploading images for verification
2. Batch processing multiple images
3. Retrieving verification logs
4. Getting system statistics

The verification process:
1. Client uploads image via POST /upload
2. Server validates file type and size
3. Image is saved to temporary storage
4. YOLO detects objects in the image
5. CLIP classifies the image
6. Results are combined (YOLO OR CLIP = valid)
7. Valid images moved to permanent storage
8. Invalid images deleted
9. Results logged to CSV
10. JSON response sent to client
"""

from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from typing import List, Dict
import logging
from contextlib import asynccontextmanager

# Import model caching FIRST to set up cache directories
# Fix the import path issue
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from model_cache import setup_model_cache, check_cached_models

from models import YOLODetector, CLIPClassifier
from utils import FileManager, setup_logger, log_verification
from config import (
    CORS_ORIGINS,
    MAX_FILE_SIZE_BYTES,
    ALLOWED_EXTENSIONS
)

# Setup logging
logger = setup_logger()

# Global model instances (loaded once at startup)
yolo_detector = None
clip_classifier = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Lifespan context manager for startup and shutdown events.
    """
    # Startup: Load AI models
    global yolo_detector, clip_classifier
    
    logger.info("Starting Property Image Verification System...")
    
    # Set up model caching to avoid re-downloading models
    logger.info("Setting up model cache...")
    cache_dir = setup_model_cache()
    cache_info = check_cached_models()
    logger.info(f"Model cache info: {cache_info}")
    
    logger.info("Loading AI models...")
    
    try:
        yolo_detector = YOLODetector()
        clip_classifier = CLIPClassifier()
        logger.info("All models loaded successfully!")
    except Exception as e:
        logger.error(f"Failed to load models: {e}")
        raise
    
    # Start background cleanup task
    import asyncio
    cleanup_task = asyncio.create_task(FileManager.cleanup_old_temp_files())
    
    yield
    
    # Shutdown
    logger.info("Shutting down server...")
    cleanup_task.cancel()


# Initialize FastAPI app
app = FastAPI(
    title="Property Image Verification API",
    description="AI-powered system to verify if uploaded images are valid property/house images",
    version="1.0.0",
    lifespan=lifespan
)

# Add CORS middleware to allow frontend communication
app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    """
    Root endpoint - API information.
    """
    return {
        "message": "Property Image Verification API",
        "version": "1.0.0",
        "endpoints": {
            "upload": "/upload",
            "batch_upload": "/batch-upload",
            "logs": "/logs",
            "stats": "/stats",
            "health": "/health"
        }
    }


@app.get("/health")
async def health_check():
    """
    Health check endpoint to verify models are loaded.
    """
    cache_info = check_cached_models()
    return {
        "status": "healthy",
        "yolo_loaded": yolo_detector is not None,
        "clip_loaded": clip_classifier is not None,
        "yolo_info": yolo_detector.get_model_info() if yolo_detector else None,
        "clip_info": clip_classifier.get_model_info() if clip_classifier else None,
        "model_cache": cache_info
    }


@app.post("/upload")
async def upload_image(file: UploadFile = File(...)):
    """
    Upload and verify a single image.
    
    Process:
    1. Validate file type and size
    2. Save to temporary storage
    3. Calculate image hash
    4. Run YOLO object detection
    5. Run CLIP classification
    6. Combine results (OR logic)
    7. Move to permanent storage if valid, delete if invalid
    8. Log results
    9. Return verification response
    
    Args:
        file: Uploaded image file (JPG/PNG)
        
    Returns:
        JSON response with validation result and details
    """
    try:
        # Validate file extension
        if not FileManager.validate_file_extension(file.filename):
            raise HTTPException(
                status_code=400,
                detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"
            )
        
        # Read file content
        file_content = await file.read()
        file_size = len(file_content)
        
        # Validate file size
        if not FileManager.validate_file_size(file_size, MAX_FILE_SIZE_BYTES):
            raise HTTPException(
                status_code=400,
                detail=f"File too large. Maximum size: {MAX_FILE_SIZE_BYTES / (1024*1024)}MB"
            )
        
        # Generate unique filename and save to temp storage
        unique_filename = FileManager.generate_unique_filename(file.filename)
        temp_path = await FileManager.save_temp_file(file_content, unique_filename)
        
        image_hash = FileManager.calculate_image_hash(str(temp_path))
        
        logger.info(f"Processing image: {unique_filename}")
        
        # Run YOLO detection on the temporary file
        yolo_valid, yolo_detections, yolo_objects = yolo_detector.detect_objects(str(temp_path))
        
        # Run CLIP classification on the temporary file
        clip_valid, clip_probs, clip_prediction = clip_classifier.classify_image(str(temp_path))
        
        # Combine results: Valid if YOLO OR CLIP indicates property
        is_valid = yolo_valid or clip_valid
        
        # Determine final decision message
        if is_valid:
            if yolo_valid and clip_valid:
                decision = "Valid property image (confirmed by both YOLO and CLIP)"
            elif yolo_valid:
                decision = "Valid property image (confirmed by YOLO object detection)"
            else:
                decision = "Valid property image (confirmed by CLIP classification)"
            
            # Move to permanent storage
            valid_path = FileManager.move_to_valid_storage(temp_path)
            message = "✅ Valid property image"
        else:
            decision = "Invalid image - no property indicators detected"
            # Delete invalid image
            FileManager.delete_file(temp_path)
            message = "❌ Invalid image, please upload a real property photo"
        
        # Log verification
        log_verification(
            filename=unique_filename,
            is_valid=is_valid,
            yolo_objects=yolo_objects,
            clip_probabilities=clip_probs,
            clip_prediction=clip_prediction,
            final_decision=decision
        )
        
        # Prepare response
        response = {
            "valid": is_valid,
            "message": message,
            "filename": unique_filename,
            "details": {
                "yolo": {
                    "valid": yolo_valid,
                    "property_objects_detected": yolo_objects,
                    "all_detections": yolo_detections
                },
                "clip": {
                    "valid": clip_valid,
                    "probabilities": clip_probs,
                    "prediction": clip_prediction
                },
                "decision": decision
            }
        }
        
        logger.info(f"Verification complete: {unique_filename} - Valid: {is_valid}")
        
        return JSONResponse(content=response)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error processing upload: {e}")
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@app.post("/batch-upload")
async def batch_upload_images(files: List[UploadFile] = File(...)):
    """
    Upload and verify multiple images at once.
    
    Args:
        files: List of uploaded image files
        
    Returns:
        JSON response with results for each image
    """
    if len(files) > 10:
        raise HTTPException(
            status_code=400,
            detail="Maximum 10 files allowed per batch"
        )
    
    results = []
    
    for file in files:
        try:
            # Process each file using the same logic as single upload
            # Validate file extension
            if not FileManager.validate_file_extension(file.filename):
                results.append({
                    "filename": file.filename,
                    "valid": False,
                    "message": "Invalid file type",
                    "error": True
                })
                continue
            
            # Read file content
            file_content = await file.read()
            file_size = len(file_content)
            
            # Validate file size
            if not FileManager.validate_file_size(file_size, MAX_FILE_SIZE_BYTES):
                results.append({
                    "filename": file.filename,
                    "valid": False,
                    "message": "File too large",
                    "error": True
                })
                continue
            
            # Generate unique filename and save
            unique_filename = FileManager.generate_unique_filename(file.filename)
            temp_path = await FileManager.save_temp_file(file_content, unique_filename)
            
            image_hash = FileManager.calculate_image_hash(str(temp_path))
            
            # Run verification on the temporary file
            yolo_valid, yolo_detections, yolo_objects = yolo_detector.detect_objects(str(temp_path))
            clip_valid, clip_probs, clip_prediction = clip_classifier.classify_image(str(temp_path))
            
            is_valid = yolo_valid or clip_valid
            
            if is_valid:
                # Move to permanent storage
                valid_path = FileManager.move_to_valid_storage(temp_path)
                message = "✅ Valid property image"
            else:
                FileManager.delete_file(temp_path)
                message = "❌ Invalid image"
            
            # Log verification
            log_verification(
                filename=unique_filename,
                is_valid=is_valid,
                yolo_objects=yolo_objects,
                clip_probabilities=clip_probs,
                clip_prediction=clip_prediction,
                final_decision=message
            )
            
            results.append({
                "filename": file.filename,
                "unique_filename": unique_filename,
                "valid": is_valid,
                "message": message,
                "details": {
                    "yolo": {
                        "valid": yolo_valid,
                        "property_objects_detected": yolo_objects
                    },
                    "clip": {
                        "valid": clip_valid,
                        "probabilities": clip_probs
                    }
                },
                "error": False
            })
            
        except Exception as e:
            logger.error(f"Error processing {file.filename}: {e}")
            results.append({
                "filename": file.filename,
                "valid": False,
                "message": f"Error: {str(e)}",
                "error": True
            })
    
    return JSONResponse(content={"results": results, "total": len(files)})


@app.get("/logs")
async def get_logs(limit: int = 50):
    """
    Retrieve recent verification logs.
    
    Args:
        limit: Maximum number of logs to return (default: 50)
        
    Returns:
        JSON response with verification logs
    """
    from utils.logger import get_verification_logs
    
    logs = get_verification_logs(limit)
    return JSONResponse(content={"logs": logs, "count": len(logs)})


@app.get("/stats")
async def get_stats():
    """
    Get system statistics including storage usage.
    
    Returns:
        JSON response with system statistics
    """
    storage_stats = FileManager.get_storage_stats()
    
    return JSONResponse(content={
        "storage": storage_stats,
        "models": {
            "yolo": yolo_detector.get_model_info() if yolo_detector else None,
            "clip": clip_classifier.get_model_info() if clip_classifier else None
        }
    })


if __name__ == "__main__":
    import uvicorn
    from config import HOST, PORT
    
    uvicorn.run(
        "main:app",
        host=HOST,
        port=PORT,
        reload=True,
        log_level="info"
    )