# -*- coding: utf-8 -*-
import os
import sys
import time
import base64
import json
import re
import logging

# ==================== 0. 自动依赖检查 ====================
try:
    import ddddocr
    from flask import Flask, request
except ImportError:
    print("\033[1;31m" + "="*50)
    print("错误: 缺少必要库！请执行: pip install ddddocr flask")
    print("!"*50 + "\033[0m")
    sys.exit(1)

# ==================== 1. 环境配置 (强制 CPU) ====================
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ["ORT_PROVIDERS"] = "CPUExecutionProvider"

app = Flask(__name__)
logging.getLogger('werkzeug').setLevel(logging.ERROR)

# 默认认证信息
AUTH_BASE64 = "f0ngauth"

# ==================== 2. 初始化双引擎 (解决污染问题) ====================
print("\033[1;36m" + "="*50 + "\033[0m")
try:
    # 引擎 A：常规模式专用，严禁调用 set_ranges
    ocr_std = ddddocr.DdddOcr(show_ad=False, beta=True)
    # 引擎 B：分类模式专用，随意切换模式
    ocr_classed = ddddocr.DdddOcr(show_ad=False, beta=True)
    print("\033[1;32m[+] 双引擎架构已启动：常规模式与分类模式已完全隔离\033[0m")
except Exception as e:
    print(f"[-] 初始化失败: {e}")
    sys.exit(1)

# ==================== 3. 核心工具函数 ====================

def get_image_bytes():
    try:
        raw_data = request.get_data(as_text=True).strip()
        if not raw_data: return None
        if raw_data.startswith('{'):
            try:
                js = json.loads(raw_data)
                raw_data = js.get("base64") or js.get("data") or raw_data
            except: pass
        if "," in raw_data:
            raw_data = raw_data.split(",")[1]
        # 强力过滤非 Base64 字符
        clean_b64 = re.sub(r'[^A-Za-z0-9+/=]', '', raw_data)
        return base64.b64decode(clean_b64)
    except Exception as e:
        print(f"[-] 解析失败: {e}")
        return None

def check_auth():
    auth = request.headers.get('Authorization', '')
    return auth.replace(" ", "") == f"Basic{AUTH_BASE64}"

# ==================== 4. 路由处理逻辑 ====================

@app.route('/reg', methods=['POST'])
def reg_standard():
    """ 
    常规识别：使用独占的 ocr_std 引擎
    """
    if not check_auth(): return "Forbidden", 403
    img = get_image_bytes()
    if not img: return "No Data", 400
    
    # 永远不调用 set_ranges
    res = ocr_std.classification(img)
    final_res = res[0:10] if res else ""
    print(f"[{time.strftime('%H:%M:%S')}] [常规引擎] -> {final_res}")
    return final_res

def classed_handler(mode):
    """ 
    分类识别：使用专用的 ocr_classed 引擎
    """
    if not check_auth(): return "Forbidden", 403
    img = get_image_bytes()
    if not img: return "No Data", 400
    
    ocr_classed.set_ranges(mode)
    res = ocr_classed.classification(img)
    final_res = res[0:10] if res else ""
    print(f"[{time.strftime('%H:%M:%S')}] [分类引擎:模式{mode}] -> {final_res}")
    return final_res

# --- 分类路由映射 ---
@app.route('/reg00', methods=['POST'])
def reg00(): return classed_handler(0)
@app.route('/reg01', methods=['POST'])
def reg01(): return classed_handler(1)
@app.route('/reg02', methods=['POST'])
def reg02(): return classed_handler(2)
@app.route('/reg03', methods=['POST'])
@app.route('/reg3', methods=['POST'])
def reg03(): return classed_handler(3)
@app.route('/reg04', methods=['POST'])
def reg04(): return classed_handler(4)
@app.route('/reg05', methods=['POST'])
def reg05(): return classed_handler(5)
@app.route('/reg06', methods=['POST'])
@app.route('/reg6', methods=['POST'])
def reg06(): return classed_handler(6)

@app.route('/reg2', methods=['POST'])
def reg_math():
    """ 算术识别：同样使用隔离的引擎 """
    if not check_auth(): return "Forbidden", 403
    img = get_image_bytes()
    if not img: return "Error", 400
    # 算术建议使用常规引擎识别，因为它最全
    res = ocr_std.classification(img).lower().replace("=", "").replace("?", "").replace("x", "*")
    try:
        for op in ['+', '-', '*']:
            if op in res:
                p = res.split(op)
                n1 = int("".join(filter(str.isdigit, p[0])))
                n2 = int("".join(filter(str.isdigit, p[1])))
                v = (n1 + n2) if op=='+' else (n1 - n2) if op=='-' else (n1 * n2)
                return str(v)
    except: pass
    return res

# ==================== 5. 启动 ====================
if __name__ == '__main__':
    PORT = 8888
    print("\033[1;35m" + "="*50)
    print(f"🚀 双引擎隔离版已启动: http://127.0.0.1:{PORT}")
    print(f"💡 说明：常规模式与分类模式互不干扰")
    print("="*50 + "\033[0m")
    app.run(host='0.0.0.0', port=PORT, threaded=True)
