# main.py

from flask import Flask, request, jsonify
from translate import translate_text

app = Flask(__name__)


@app.route('/translate', methods=['POST'])
def translate_api():
    """
    多语言翻译接口
    请求体示例:
    {
        "text": "Hello world",
        "source_lang": "en",   // 可选，默认 auto
        "target_lang": "zh"    // 可选，默认 zh
    }
    """
    data = request.get_json()
    if not data or 'text' not in data:
        return jsonify({"error": "缺少参数 'text'"}), 400

    text = data['text']
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'zh')

    result = translate_text(text, source_lang, target_lang)

    if result['success']:
        return jsonify({
            "translated_text": result['translated_text'],
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    else:
        return jsonify({"error": result['error']}), 400


@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({"status": "ok", "service": "baidu-translate"})


@app.route('/', methods=['GET'])
def index():
    return jsonify({
        "message": "Baidu Translate API Service",
        "endpoints": {
            "translate": "POST /translate",
            "health": "GET /health"
        }
    })


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