# auth/auth_handlers.py
import json
import os
import sys
import requests
import urllib.request
import urllib.error
from urllib.parse import urljoin

def login_handler(json_payload, base_url, data_cache_dir):
    """處理用戶登錄請求"""
    # 1. 动态获取完整的 API URL
    base = base_url.strip().rstrip('/')
    endpoint = "auth/login"
    url = f"{base}/{endpoint}"
    
    # 2. 解析从 Electron 传过来的参数
    try:
        input_data = json.loads(json_payload)
        payload = {
            "phone": input_data.get('phone'),
            "password": input_data.get('password')
        }
    except Exception as e:
        raise ValueError(f"解析登录参数失败: {str(e)}")

    # 3. 设置请求头
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "BigBear-Client/1.0"
    }

    try:
        # 4. 执行 POST 请求
        response = requests.post(url, json=payload, headers=headers, timeout=10)
        
        # 5. 检查是否返回了 HTML
        if "text/html" in response.headers.get("Content-Type", ""):
            raise ValueError("服务器路径配置错误或接口被拦截")

        # 6. 解析响应
        res_body = response.json()

        # 7. 处理成功响应
        if res_body.get("success") == True:
            token = res_body.get("token")
            if token:
                # 保存 Token 到本地缓存
                token_path = os.path.join(data_cache_dir, "user_token.json")
                os.makedirs(data_cache_dir, exist_ok=True)
                with open(token_path, 'w', encoding='utf-8') as f:
                    json.dump({
                        "token": token, 
                        "user": res_body.get("name", ""),
                        "id": res_body.get("id", "")
                    }, f)
        
        return res_body

    except requests.exceptions.RequestException as e:
        raise ConnectionError(f"无法连接到比格熊云端服务器: {str(e)}")
    except json.JSONDecodeError:
        raise ValueError("服务器响应数据格式异常")

def reg_handler(json_payload, base_url, data_cache_dir):
    """處理用戶註冊請求"""
    url = f"{base_url}auth/register"
    
    try:
        data = json.loads(json_payload)
        username = data.get('username')
        password = data.get('password')
        phone = data.get('phone')
        confirm_password = data.get('confirmPassword')

        payload = {
            "username": username,
            "password": password,
            "phone": phone,
            "confirm_password": confirm_password
        }

        data = json.dumps(payload).encode('utf-8')
        req = urllib.request.Request(url, data=data, method='POST')
        req.add_header('Content-Type', 'application/json')
        
        with urllib.request.urlopen(req, timeout=5) as response: 
            raw_content = response.read().decode('utf-8')
            res_body = json.loads(raw_content)
            
            if res_body.get("success"):
                # 保存 Token 到本地缓存，实现自动登录
                token = res_body.get("token")
                if token:
                    token_path = os.path.join(data_cache_dir, "user_token.json")
                    os.makedirs(data_cache_dir, exist_ok=True)
                    with open(token_path, 'w', encoding='utf-8') as f:
                        json.dump({"token": token, "user": username}, f)
            
            return res_body

    except urllib.error.HTTPError as e:
        try:
            error_raw = e.read().decode('utf-8-sig').strip()
            error_body = json.loads(error_raw)
            return {
                "success": False, 
                "message": error_body.get("message", f"注册失败({e.code})")
            }
        except:
            return {"success": False, "message": f"服务器连接失败({e.code})"}

    except Exception as e:
        raise Exception(f"注册组件异常: {str(e)}")

def activate_handler(json_payload, base_url, data_cache_dir):
    """處理用戶激活請求"""
    final_result = {
        "success": False,
        "status": 500,
        "message": "未知错误",
        "data": None
    }

    try:
        # 1. 解析前端传入参数
        try:
            input_data = json.loads(json_payload)
        except Exception:
            final_result["message"] = "前端参数格式错误"
            return final_result

        token = input_data.get('token')
        code = input_data.get('code')
        activate_url = input_data.get('activate_url')
        
        if not activate_url:
            activate_url = f"{base_url}auth/activate"
            
        url = f"{activate_url}?acode={code}"

        # 构造 Body
        payload = {
            "token": token,
            "acode": code
        }
        encoded_data = json.dumps(payload).encode('utf-8')

        # 2. 构造请求
        req = urllib.request.Request(url, data=encoded_data, method='POST')
        req.add_header('Content-Type', 'application/json')
        if token:
            req.add_header('Authorization', f"Bearer {token}")
        
        # 3. 发送请求
        try:
            with urllib.request.urlopen(req, timeout=10) as response:
                raw_content = response.read().decode('utf-8')
                server_res = json.loads(raw_content)
                
                # 直接透传服务器的所有字段
                final_result.update(server_res)
                if server_res.get("status") == "OK" or server_res.get("success") is True:
                    final_result["success"] = True
                
                return final_result

        except urllib.error.HTTPError as e:
            error_raw = e.read().decode('utf-8-sig', errors='ignore').strip()
            
            # 检查是否返回了 HTML
            if error_raw.startswith("<!DOCTYPE") or "<html" in error_raw:
                final_result["status"] = e.code
                final_result["message"] = f"服务器响应异常(HTML)，请检查是否需要重新登录(错误码:{e.code})"
                return final_result

            try:
                error_body = json.loads(error_raw)
                final_result["message"] = error_body.get("message", f"激活失败({e.code})")
                final_result["status"] = e.code
                if "needAuth" in error_body: 
                    final_result["needAuth"] = error_body["needAuth"]
            except:
                final_result["message"] = f"请求失败: {error_raw[:50] if error_raw else e.reason}"
                final_result["status"] = e.code
            
            return final_result

    except Exception as e:
        final_result["message"] = "别闹！请输入正确的激活码！"
        return final_result