#!/usr/bin/env python3
"""
Maya Negosyo API 本地代理服务器
- 提供 maya-login-test.html 静态文件
- 将 /proxy/* 请求转发到远程 API，绕过浏览器 CORS 限制

用法: python3 maya-login-proxy.py
然后浏览器打开 http://localhost:8856/maya-login-test.html
"""

import http.server
import urllib.request
import urllib.error
import os
import sys
from urllib.parse import urlsplit

# ==================== 配置 ====================
REMOTE_API = "http://35.187.240.132:6007"
LOCAL_PORT = 8856
STATIC_DIR = os.path.dirname(os.path.abspath(__file__))
# ==================== 配置结束 ====================


class ProxyHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=STATIC_DIR, **kwargs)

    def do_GET(self):
        """静态文件由父类处理; /proxy/* 转发"""
        if self.path.startswith("/proxy/"):
            self._forward("GET")
        else:
            super().do_GET()

    def do_POST(self):
        """所有 POST 都走代理转发"""
        if self.path.startswith("/proxy/"):
            self._forward("POST")
        else:
            self._send_json(404, {"error": "Not Found"})

    def do_OPTIONS(self):
        """处理 CORS 预检请求"""
        self.send_response(204)
        self._set_cors_headers()
        self.end_headers()

    def _forward(self, method):
        # 去掉 /proxy 前缀，得到真实 API 路径
        parts = urlsplit(self.path)
        api_path = parts.path[len("/proxy"):]  # 如 /login
        if parts.query:
            api_path += "?" + parts.query

        target_url = REMOTE_API + api_path

        # 读取请求体
        content_length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(content_length) if content_length > 0 else None

        # 构建转发请求
        req = urllib.request.Request(target_url, data=body, method=method)
        req.add_header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")

        # 透传 Authorization
        auth = self.headers.get("Authorization")
        if auth:
            req.add_header("Authorization", auth)

        print(f"[{method}] {target_url}", flush=True)

        try:
            with urllib.request.urlopen(req, timeout=60) as resp:
                resp_body = resp.read()
                self._send_response(resp.status, resp_body, resp.headers.get("Content-Type", "application/json"))
        except urllib.error.HTTPError as e:
            resp_body = e.read()
            self._send_response(e.code, resp_body, e.headers.get("Content-Type", "application/json"))
        except Exception as e:
            err = f'{{"code":-1,"error":"{e}","status_code":0}}'.encode()
            self._send_response(502, err, "application/json")

    def _send_response(self, code, body, content_type):
        self.send_response(code)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self._set_cors_headers()
        self.end_headers()
        self.wfile.write(body)

    def _send_json(self, code, obj):
        import json
        body = json.dumps(obj).encode()
        self._send_response(code, body, "application/json")

    def _set_cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")

    def log_message(self, format, *args):
        pass  # 静默默认日志，用上面的 print 替代


def main():
    print("=" * 50)
    print("  Maya Negosyo API 本地代理服务器")
    print("=" * 50)
    print(f"  远程 API : {REMOTE_API}")
    print(f"  本地端口 : {LOCAL_PORT}")
    print(f"  静态目录 : {STATIC_DIR}")
    print()
    print(f"  浏览器打开: http://localhost:{LOCAL_PORT}/maya-login-test.html")
    print("=" * 50)
    print()

    server = http.server.HTTPServer(("0.0.0.0", LOCAL_PORT), ProxyHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器已停止。")
        server.server_close()


if __name__ == "__main__":
    main()
