import os
import sys
import asyncio
from datetime import datetime
from typing import Dict, Any, Optional

import uvicorn
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from pydantic import BaseModel, ValidationError
from loguru import logger

# Configure logging
logger.remove()
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")

# Pydantic models
class HealthResponse(BaseModel):
    status: str
    service: str
    timestamp: str
    version: str
    uptime: float

class ServiceRequest(BaseModel):
    project_id: Optional[str] = None
    data: Dict[str, Any] = {}
    metadata: Dict[str, Any] = {}

class ServiceResponse(BaseModel):
    success: bool
    data: Dict[str, Any] = {}
    message: str = ""
    timestamp: str = ""

# Initialize FastAPI app
app = FastAPI(
    title="test-generator",
    description="test-generator service for automated development pipeline",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# Add middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"]
)

# Global variables
start_time = datetime.utcnow()

# Routes
@app.get("/health", response_model=HealthResponse)
async def health_check():
    """Comprehensive health check endpoint"""
    uptime = (datetime.utcnow() - start_time).total_seconds()
    
    return HealthResponse(
        status="healthy",
        service="test-generator",
        timestamp=datetime.utcnow().isoformat(),
        version="1.0.0",
        uptime=uptime
    )

@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": "test-generator is running",
        "service": "test-generator",
        "status": "active",
        "timestamp": datetime.utcnow().isoformat(),
        "version": "1.0.0"
    }

@app.get("/api/v1/status")
async def service_status():
    """Detailed service status endpoint"""
    uptime = (datetime.utcnow() - start_time).total_seconds()
    
    return {
        "service": "test-generator",
        "status": "ready",
        "capabilities": [
            "health_check",
            "status_check",
            "async_processing"
        ],
        "uptime": uptime,
        "timestamp": datetime.utcnow().isoformat(),
        "version": "1.0.0"
    }

@app.post("/api/v1/process", response_model=ServiceResponse)
async def process_request(request: ServiceRequest, background_tasks: BackgroundTasks):
    """Main processing endpoint for test-generator"""
    try:
        logger.info(f"Processing request for project: {request.project_id}")
        
        # Simulate processing
        await asyncio.sleep(0.1)
        
        response_data = {
            "processed": True,
            "service": "test-generator",
            "project_id": request.project_id,
            "input_data_keys": list(request.data.keys()) if request.data else []
        }
        
        return ServiceResponse(
            success=True,
            data=response_data,
            message="Request processed successfully by test-generator",
            timestamp=datetime.utcnow().isoformat()
        )
        
    except Exception as e:
        logger.error(f"Error processing request: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Processing failed: {str(e)}"
        )

@app.get("/api/v1/cache/{project_id}")
async def get_cached_result(project_id: str):
    """Get cached result for a project"""
    return {
        "found": False,
        "message": "Cache not implemented yet",
        "project_id": project_id,
        "timestamp": datetime.utcnow().isoformat()
    }

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8005))
    log_level = os.getenv("LOG_LEVEL", "info")
    
    logger.info(f"Starting test-generator on port {port}")
    
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=port,
        reload=False,
        log_level=log_level,
        access_log=True
    )