from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
import os
import logging

app = FastAPI()

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Directory where the audio files are stored
AUDIO_DIR = "/var/www/html/wordnet/audio"

@app.get("/audio/{word_id_str}")
def get_audio(word_id_str: str):
    """ Serve a WAV audio file with forced download """

    # Remove .wav extension if present
    word_id_str = word_id_str.removesuffix(".wav")

    try:
        word_id = int(word_id_str)  # Validate input as an integer
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid word ID format")

    # Construct absolute file path securely
    file_path = os.path.join(AUDIO_DIR, f"{word_id}.wav")
    file_path = os.path.abspath(file_path)
    
    # Log the file existence status
    exists = os.path.exists(file_path)
    logger.info(f"Checking file: {file_path} exists: {exists}")

    # Prevent directory traversal attacks and check file existence
    if not file_path.startswith(AUDIO_DIR) or not exists:
        raise HTTPException(status_code=404, detail="Audio file not found")

    logger.info(f"Serving file: {file_path}")  # Debug log

    # Set headers to force download
    headers = {
        "Content-Disposition": f"attachment; filename={word_id}.wav",
        "Content-Type": "audio/wav",
    }

    return FileResponse(file_path, headers=headers)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=3000)
