#!/usr/bin/env python3
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import whisper
import os
import tempfile

app = Flask(__name__, static_folder='.', static_url_path='')
CORS(app)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50MB max (audio only)

@app.after_request
def set_headers(response):
    response.headers['Cross-Origin-Opener-Policy'] = 'same-origin'
    response.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'
    return response

print("Loading Whisper model...")
model = whisper.load_model("base")
print("Model loaded!")

@app.route('/')
def index():
    response = send_from_directory('.', 'index.html')
    response.headers['Cross-Origin-Opener-Policy'] = 'same-origin'
    response.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'
    return response

@app.route('/<path:filename>')
def static_files(filename):
    response = send_from_directory('.', filename)
    response.headers['Cross-Origin-Opener-Policy'] = 'same-origin'
    response.headers['Cross-Origin-Embedder-Policy'] = 'require-corp'
    return response

@app.route('/transcribe', methods=['POST'])
def transcribe():
    try:
        if 'file' not in request.files:
            return jsonify({'error': 'No file provided'}), 400

        file = request.files['file']
        language = request.form.get('language', None)

        if language:
            language = language.split('-')[0].lower()

        if file.filename == '':
            return jsonify({'error': 'No file selected'}), 400

        # Enforce audio-only uploads (per DEVELOPMENT_RULES.md)
        ext = os.path.splitext(file.filename)[1].lower()
        video_exts = {'.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm'}
        if ext in video_exts:
            return jsonify({'error': 'Video files not allowed. Extract audio first.'}), 400

        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp:
            filepath = tmp.name
            file.save(filepath)

        result = model.transcribe(filepath, language=language)
        os.remove(filepath)

        return jsonify({'text': result['text']})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=False, port=5000, host='127.0.0.1')
