# server.py
from flask import Flask, request, jsonify
from loguru import logger
# 引入逻辑类
from inv_img_double_search import AmazonImageSearch, SITE_CONFIG_MAPPER

app = Flask(__name__)

# 让 Flask 支持中文返回不乱码
app.config['JSON_AS_ASCII'] = False


# ==========================================
#  新增：首页接口 (浏览器直接访问)
# ==========================================
@app.route('/', methods=['GET'])
def index():
    """
    首页：显示服务状态和简易文档
    """
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Amazon 以图搜图服务</title>
        <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 40px; line-height: 1.6; color: #333; }
            .container { background: #f9f9fa; padding: 30px; border-radius: 10px; border: 1px solid #e1e4e8; }
            h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
            .status { color: #27ae60; font-weight: bold; font-size: 1.2em; }
            .endpoint { background: #2c3e50; color: #fff; padding: 5px 10px; border-radius: 4px; font-family: monospace; }
            .method { background: #e67e22; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.8em; font-weight: bold; }
            pre { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 5px; overflow-x: auto; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>📸 Amazon Image Search API</h1>
            <p>状态：<span class="status">✅ 服务正在运行 (Service is Running)</span></p>

            <h3>接口信息</h3>
            <p>URL: <span class="endpoint">/api/search_image</span> <span class="method">POST</span></p>

            <h3>请求示例 (JSON)</h3>
            <pre>
{
    "image_url": "https://m.media-amazon.com/images/I/51i3aMcjmOL._SL600_.jpg",
    "site_name": "us",     // 可选: us
    "search_mode": "default" // 可选: default, full_image
}
            </pre>

            <h3>健康检查</h3>
            <p>URL: <a href="/health">/health</a> <span class="method">GET</span></p>
        </div>
    </body>
    </html>
    """
    return html_content


# ==========================================
#  核心业务接口
# ==========================================
@app.route('/api/search_image', methods=['POST'])
def search_image_api():
    """
    接口描述：Amazon 以图搜图
    Method: POST
    """
    # 1. 获取并校验 JSON
    data = request.get_json(silent=True)
    if not data:
        return jsonify({"code": 400, "msg": "Body必须是JSON格式"}), 400

    # 2. 提取参数
    image_url = data.get("image_url")
    site_name = data.get("site_name", "us")
    search_mode = data.get("search_mode", "default")

    # 3. 校验必填项
    if not image_url:
        return jsonify({"code": 400, "msg": "缺少参数: image_url"}), 400

    if site_name not in SITE_CONFIG_MAPPER:
        return jsonify({"code": 400, "msg": f"不支持的站点: {site_name}，支持: {list(SITE_CONFIG_MAPPER.keys())}"}), 400

    try:
        logger.info(f"收到API请求: Site={site_name}, Mode={search_mode}, URL={image_url}")

        # 4. 初始化并执行搜索
        client = AmazonImageSearch(site_name=site_name)
        result = client.search(image_url, search_mode=search_mode)

        # 5. 判断业务是否成功
        if result.get("error") or result.get("success") == 0:
            return jsonify({"code": 500, "msg": "识别失败", "data": result}), 500

        return jsonify({"code": 200, "msg": "success", "data": result})

    except Exception as e:
        logger.error(f"服务内部错误: {e}")
        return jsonify({"code": 500, "msg": f"Server Error: {str(e)}"}), 500


@app.route('/health', methods=['GET'])
def health():
    """健康检查接口"""
    return jsonify({"status": "ok", "service": "Amazon Image Search"})


if __name__ == "__main__":
    # 启动服务
    logger.info("Flask 服务正在启动...")
    # logger.info("请访问 http://127.0.0.1:5000 查看首页")
    app.run(host='0.0.0.0', port=5000, debug=False)