# network/api_client.py
import json
import urllib.request
import urllib.error
from urllib.parse import urlencode, urljoin
from config import get_base_url, get_config

BASE_URL = get_base_url()
config = get_config()

def fetch_json_handler(payload_str, base_url):
    """
    请求远程 JSON API 并返回解析后的 JSON 数据。
    输入 payload_str 应为 JSON 字符串，格式：
    {
        "url": "https://api.example.com/data",
        "token": "optional_jwt_token"
    }

    返回：JSON 字符串，格式：
    {
        "status": "200",
        "success": true,
        "data": { ... }  // 这里是解析后的 JSON 对象
    }
    或
    {
        "status": "401",
        "success": false,
        "message": "错误信息",
        "data": null
    }
    """
    try:
        payload = json.loads(payload_str)
        remote_url = payload.get("url", "").strip()
        token = payload.get("token", "").strip()

        if not remote_url:
            raise ValueError("Missing required field: 'url'")

        req = urllib.request.Request(remote_url)
        if token:
            req.add_header('Authorization', f'Bearer {token}')
        req.add_header('User-Agent', 'Mozilla/5.0 (compatible; MediaTool/1.0)')
        req.add_header('Accept', 'application/json')  # 明确期望 JSON

        with urllib.request.urlopen(req, timeout=15) as response:
            content_type = response.headers.get('Content-Type', '').lower()
            encoding = 'utf-8'
            if 'charset=' in content_type:
                encoding = content_type.split('charset=')[-1].split(';')[0].strip() 

            raw_body = response.read().decode(encoding, errors='replace')

            # 尝试解析 JSON
            try:
                parsed_data = json.loads(raw_body)
            except json.JSONDecodeError as je:
                raise ValueError(f"响应不是有效的 JSON: {str(je)}")

            result = {
                "status": str(response.status),
                "success": True,
                "data": parsed_data
            }
            return json.dumps(result, ensure_ascii=False)

    except urllib.error.HTTPError as e:
        status_code = e.code
        try:
            error_body = e.read().decode('utf-8')
            # 尝试解析错误响应中的 JSON
            if error_body.strip().startswith('{'):
                err_json = json.loads(error_body)
                message = err_json.get("message") or f"HTTP {status_code} 错误"
            else:
                message = f"服务器返回错误（{status_code}）: {error_body[:100].strip()} "
        except Exception:
            message = f"请求失败，HTTP 状态码: {status_code}"

        result = {
            "status": str(status_code),
            "success": False,
            "message": message,
            "data": None
        }
        return json.dumps(result, ensure_ascii=False)

    except urllib.error.URLError as e:
        result = {
            "status": "0",
            "success": False,
            "message": f"网络连接失败: {str(e.reason)}",
            "data": None
        }
        return json.dumps(result, ensure_ascii=False)

    except Exception as e:
        result = {
            "status": "500",
            "success": False,
            "message": f"内部错误: {str(e)}",
            "data": None
        }
        return json.dumps(result, ensure_ascii=False)

def fetch_html_handler(payload_str):
    try:
        payload = json.loads(payload_str)
        remote_url = payload.get("url", "").strip()
        token = payload.get("token", "").strip()

        if not remote_url:
            raise ValueError("Missing required field: 'url'")

        req = urllib.request.Request(remote_url)
        if token:
            req.add_header('Authorization', f'Bearer {token}')
            req.add_header('User-Agent', 'Mozilla/5.0 (compatible; MediaTool/1.0)')

        with urllib.request.urlopen(req, timeout=15) as response:
            content_type = response.headers.get('Content-Type', '').lower()
            encoding = 'utf-8'
            if 'charset=' in content_type:
                encoding = content_type.split('charset=')[-1].split(';')[0].strip()

            raw_html = response.read().decode(encoding, errors='replace')

            return {
                "status": str(response.status),
                "success": True,
                "data": raw_html
            }

    except urllib.error.HTTPError as e:
        status_code = e.code
        try:
            error_body = e.read().decode('utf-8')
            if error_body.strip().startswith('{'):
                import json as json_mod
                err_json = json_mod.loads(error_body)
                message = err_json.get("message") or f"HTTP {status_code} 错误"
            else:
                message = f"服务器返回错误（{status_code}）: {error_body[:100].strip()} "
        except Exception:
            message = f"请求失败，HTTP 状态码: {status_code}"

        return {
            "status": str(status_code),
            "success": False,
            "message": message,
            "data": ""
        }

    except urllib.error.URLError as e:
        return {
            "status": "0",
            "success": False,
            "message": f"网络连接失败: {str(e.reason)}",
            "data": ""
        }

    except Exception as e:
        return {
            "status": "500",
            "success": False,
            "message": f"内部错误: {str(e)}",
            "data": ""
        }

def sfx_list_handler(payload_str, base_url):
    """处理音频列表的请求"""
    payload = json.loads(payload_str)
    _url = payload.get("url", "").strip()
    token = payload.get("token", "").strip()
    kw = payload.get("kw", "").strip()

    if not kw:
        url = _url
    else:
        query = urlencode({'kw': kw})
        # 检查原始 URL 是否已经包含问号
        separator = "&" if "?" in _url else "?"
        url = f"{_url}{separator}{query}"
        
    # 构建请求头
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    try:
        req = urllib.request.Request(url, headers=headers, method='GET')
        
        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"):
                return res_body
            else:
                raise ValueError(res_body.get("message", "获取音效列表失败"))
                
    except urllib.error.URLError as e:
        raise ConnectionError(f"无法连接到服务器: {str(e)}")

def hot_tags_handler() -> dict:
    """處理獲取热门标签请求"""
    url = urljoin(BASE_URL, config.get('hot_tags_endpoint'))
    # 構建請求頭，包含 token
    headers = {
        # "Authorization": f"Bearer {token}"
    }
    try:
        req = urllib.request.Request(url, headers=headers, method='GET')
        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"):
                return res_body
            else:
                raise ValueError(res_body.get("message", "获取热门标签失败"))
    except urllib.error.URLError as e:
        raise ConnectionError(f"无法连接到服务器: {str(e)}")    