#!/usr/bin/env python3
"""
RingAI - AI-powered IVR System

Main entry point for the FastAPI application.
"""

import asyncio
from fastapi import FastAPI

from ringai.config import (
    validate_twilio_credentials,
    ensure_directories,
    log_call,
    STALE_CALL_TIMEOUT_SEC,
)
from ringai.api import router, websocket_router
from ringai.dialogue import call_state_manager
from ringai.storage import get_data_store
from ringai.stt import get_transcriber

# Validate configuration on import
validate_twilio_credentials()
ensure_directories()

# Create FastAPI app
app = FastAPI(
    title="RingAI",
    description="AI-powered IVR System for ERP/CRM Sales",
    version="1.1.0",
)

# Include routers
app.include_router(router)
app.include_router(websocket_router)


# Background task for cleanup
async def cleanup_stale_calls():
    """Finalize calls that haven't reconnected in timeout period"""
    data_store = get_data_store()

    while True:
        await asyncio.sleep(10)  # Check every 10 seconds

        stale_calls = call_state_manager.cleanup_stale(STALE_CALL_TIMEOUT_SEC)

        for call_id in stale_calls:
            log_call.info("call=%s timeout detected, finalizing", call_id)

            state = call_state_manager.get(call_id)
            if state:
                # Save final transcript
                final_text = state.get_final_transcript()
                if final_text:
                    data_store.save_final_transcript(call_id, final_text)

                # Merge audio
                data_store.merge_call_audio(call_id)

            call_state_manager.remove(call_id)
            log_call.info("call=%s finalized via timeout", call_id)


@app.on_event("startup")
async def startup_event():
    """Initialize on startup"""
    # Pre-load Whisper model
    log_call.info("Pre-loading Whisper model...")
    transcriber = get_transcriber()
    transcriber.load_model()

    # Start background cleanup task
    asyncio.create_task(cleanup_stale_calls())

    log_call.info("RingAI server started")


@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    log_call.info("RingAI server shutting down")


# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "active_calls": len(call_state_manager),
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=False,
    )
