from flask import Flask, request, send_file
from flask_cors import CORS
import os
from utils.docx_translator import DocxTranslator
import shutil
import time

app = Flask(__name__)
CORS(app, resources={
    r"/*": {
        "origins": ["chrome-extension://*"],
        "methods": ["POST", "OPTIONS", "GET"],
        "allow_headers": ["Content-Type"]
    }
})

# 全局变量存储翻译进度
translation_progress = 0

UPLOAD_FOLDER = 'temp'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

def update_progress(progress):
    global translation_progress
    translation_progress = progress

@app.route('/progress', methods=['GET'])
def get_progress():
    return {'progress': translation_progress}

@app.route('/translate', methods=['POST'])
def translate_docx():
    global translation_progress
    translation_progress = 0
    input_path = None
    output_path = None
    
    if 'file' not in request.files:
        return {'error': 'No file provided'}, 400
        
    file = request.files['file']
    target_lang = request.form.get('target_lang', 'en')
    
    if file.filename == '':
        return {'error': 'No file selected'}, 400
        
    try:
        timestamp = str(int(time.time()))
        safe_filename = f"{timestamp}_{file.filename}"
        input_path = os.path.join(UPLOAD_FOLDER, safe_filename)
        file.save(input_path)
        
        translator = DocxTranslator()
        output_path = translator.translate_document(
            input_path, 
            target_lang=target_lang,
            progress_callback=update_progress
        )
        
        temp_output = output_path + '.tmp'
        shutil.copy2(output_path, temp_output)
        
        return send_file(
            temp_output,
            as_attachment=True,
            download_name=f"translated_{file.filename}"
        )
        
    except Exception as e:
        return {'error': str(e)}, 500
        
    finally:
        try:
            if input_path and os.path.exists(input_path):
                os.remove(input_path)
            if output_path and os.path.exists(output_path):
                os.remove(output_path)
            if 'temp_output' in locals() and os.path.exists(temp_output):
                os.remove(temp_output)
        except Exception as e:
            print(f"Error cleaning up files: {e}")

if __name__ == '__main__':
    app.run(debug=True, port=5000)