import sys, os
from datetime import datetime
sys.path.append(os.path.dirname(sys.path[0]))
import json
from flask import Flask, request as flask_request, Response
from utils.secure_db_client import get_remote_engine
flask_app = Flask(__name__)

def get_business_val(seller_address, key):
    parts =[p.strip()for p in seller_address.split("|-|")]
    for i, p in enumerate(parts):
        if p.startswith(key):
            if key in ("Business Address","Geschaftsadresse","Geschäftsadresse"):
                return " ".join(parts[i + 1:]).strip()
            elif i + 1 < len(parts):
                return parts[i + 1].strip()
    return None

def json_response(data):
    return Response(json.dumps(data, ensure_ascii=False), mimetype='application/json')

# 站点对应的key映射
site_key_map = {
    "us": ("Business Name", "Business Address"),
    "uk": ("Business Name", "Business Address"),
    "de": ("Geschäftsname", "Geschäftsadresse")
}

@flask_app.route('/seller/info', methods=['GET'])
def get_seller_info():
    site_name = flask_request.args.get('site_name', '').strip()
    seller_id = flask_request.args.get('seller_id', '').strip()

    if not site_name or not seller_id:
        return json_response({"code": 400, "message": "缺少参数 site_name 或 seller_id"})

    if site_name not in site_key_map:
        return json_response({"code": 400, "message": f"不支持的站点: {site_name}"})

    try:
        engine = get_remote_engine(site_name=site_name, db_type="postgresql_14")
        year = datetime.now().year
        sql = f"""SELECT seller_address FROM {site_name}_seller_account_feedback_{year}
                  WHERE seller_id = '{seller_id}' ORDER BY id DESC LIMIT 1"""
        df = engine.read_sql(sql)

        # 今年没查到，查去年
        if df.empty:
            sql = f"""SELECT seller_address FROM {site_name}_seller_account_feedback_{year - 1}
                      WHERE seller_id = '{seller_id}' ORDER BY id DESC LIMIT 1"""
            df = engine.read_sql(sql)
        print('sql::', sql)
        print('df::', df.values.tolist())
        if df.empty:
            return json_response({"code": 404, "message": "未找到该卖家信息", "data": None})

        seller_address = df.iloc[0]['seller_address']
        if not seller_address:
            return json_response({"code": 404, "message": "seller_address 为空", "data": None})

        name_key, addr_key = site_key_map.get(site_name, ("Business Name", "Business Address"))
        business_name = get_business_val(seller_address, name_key)
        business_address = get_business_val(seller_address, addr_key)

        return json_response({
            "code": 200,
            "message": "success",
            "data": {
                "business_name": business_name,
                "business_address": business_address
            }
        })
    except Exception as e:
        return json_response({"code": 500, "message": f"查询失败: {str(e)}"})


if __name__ == '__main__':
    flask_app.run('0.0.0.0', 10240)
