import os
import sys
import time
import random

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.db_connect import BaseUtils
import json
from flask import Flask, request, jsonify
import requests
import traceback

app = Flask(__name__)

ACCOUNTS = [
    ["13752682896", "YSWG2026"],
    ["15112376559", "PYB8899"],
]

RK_IDX = 'sif:current_idx'
RK_HEADERS = 'sif:headers'


def db_resin():
    return BaseUtils().redis_db()


def generate_uuid():
    uuid_template = "Sif_xxxx-xxxx-4xxx-yxxx-xxxx"

    def replace_char(c):
        r = random.randint(0, 15)
        if c == 'x':
            return hex(r)[2:]
        elif c == 'y':
            return hex((r & 0x3) | 0x8)[2:]

    return ''.join(replace_char(c) if c in 'xy' else c for c in uuid_template)


def login_slf(phone, password):
    int_time = int(time.time() * 1000)
    _m = generate_uuid()
    login_url = f'https://www.sif.com/api/user/login?_t={int_time}&_m={_m}'
    print(f'[login] account={phone}')
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "Host": "www.sif.com",
        "Origin": "https://www.sif.com",
        "Pragma": "no-cache",
        "Referer": "https://www.sif.com/",
        "Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Ch-Ua-Platform": '"Windows"',
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }
    data = {"phone": phone, "password": password}
    resp = requests.post(login_url, headers=headers, json=data, timeout=20)
    auth = resp.headers.get('authorization')
    if not auth:
        print(f'[login] 失败：{resp.text}')
        return None
    headers['authorization'] = auth
    db_resin().set(RK_HEADERS, json.dumps(headers))
    print(f'[login] OK account={phone}')
    return headers


def get_headers(invalid=False):
    """
    invalid=True : 当前账号失效，按顺序遍历下一组账号，直到某个登录成功
    invalid=False: 返回缓存的 headers，没有则登录当前下标账号
    """
    r = db_resin()
    if invalid:
        cur = int(r.get(RK_IDX) or 0)
        for offset in range(1, len(ACCOUNTS) + 1):
            idx = (cur + offset) % len(ACCOUNTS)
            result = login_slf(*ACCOUNTS[idx])
            if result:
                r.set(RK_IDX, idx)
                return result
        return None

    cached = r.get(RK_HEADERS)
    if cached:
        return json.loads(cached)
    idx = int(r.get(RK_IDX) or 0) % len(ACCOUNTS)
    return login_slf(*ACCOUNTS[idx])


@app.route('/sif/api/headers', methods=['GET'])
def api_headers():
    invalid = request.args.get('invalid') == 'true'
    try:
        headers = get_headers(invalid=invalid)
        if headers:
            return jsonify({"code": 200, "message": "success", "headers": headers})
        return jsonify({"code": 500, "message": "login failed", "headers": None})
    except Exception as e:
        print(traceback.format_exc())
        return jsonify({"code": 500, "message": str(e), "headers": None})


# 旧路由兼容：regetFlag=true 等价于 invalid=true
@app.route('/sif/api/login', methods=['GET'])
def api_login_compat():
    reget = request.args.get('regetFlag') == 'true'
    try:
        headers = get_headers(invalid=reget)
        if headers:
            return jsonify({"code": 200, "message": "success", "headers": headers})
        return jsonify({"code": 500, "message": "login failed", "headers": None})
    except Exception as e:
        print(traceback.format_exc())
        return jsonify({"code": 500, "message": str(e), "headers": None})


if __name__ == '__main__':
    app.run('0.0.0.0', 10248)
