"""Main FastAPI application for Chronara."""

import os
from pathlib import Path

from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware

from .models.audio import AudioProcessor
from .models.llm import LlamaSummarizer
from .models.transcriber import WhisperXTranscriber

app = FastAPI(title="Chronara API", version="0.1.0")

# Enable CORS for Tauri frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["tauri://localhost", "http://localhost:*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize models
# Use environment variable if set (production), otherwise use development path
models_env = os.environ.get('CHRONARA_MODELS_DIR')
if models_env:
    MODEL_DIR = Path(models_env)
else:
    MODEL_DIR = Path(__file__).parent.parent.parent / "models"

print(f"Using models directory: {MODEL_DIR}")
transcriber = WhisperXTranscriber(model_dir=MODEL_DIR)
summarizer = LlamaSummarizer(model_dir=MODEL_DIR, model_size="3B")
audio_processor = AudioProcessor()


@app.get("/health")
async def health_check():
    """Check if the API is running and models are loaded."""
    return {
        "status": "healthy",
        "models": {
            "whisper": transcriber.is_loaded,
            "llama": summarizer.is_loaded,
        },
    }


@app.websocket("/ws/transcribe")
async def transcribe_audio(websocket: WebSocket):
    """WebSocket endpoint for real-time audio transcription."""
    await websocket.accept()

    try:
        while True:
            # Receive audio chunk
            audio_data = await websocket.receive_bytes()

            # Process audio
            audio_chunk = audio_processor.process_chunk(audio_data)

            # Transcribe if we have enough audio
            if audio_processor.has_speech(audio_chunk):
                result = await transcriber.transcribe_chunk(audio_chunk)

                if result:
                    await websocket.send_json({
                        "type": "transcription",
                        "data": result,
                    })

    except Exception as e:
        await websocket.close(code=1000, reason=str(e))


@app.post("/summarize")
async def summarize_transcript(transcript: str):
    """Summarize a meeting transcript."""
    summary = await summarizer.summarize(transcript)
    return {"summary": summary}