#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPU 儀表板統一網關（方案 B 數據源）
同時提供：
  GET /                    -> 跳轉到 /gpu_dashboard.html
  GET /gpu_dashboard.html  -> 返回儀表板 HTML（靜態）
  GET /gpu_metric.py       -> 執行 gpu_metric.py，回傳 JSON（讓儀表板能抓到資料）

目的：python3 -m http.server 不會執行 Python，只回傳源碼。
此網關讓 /gpu_metric.py 真正回傳 JSON，解決儀表板「連線中斷」。

用法：
  python3 gpu_gateway.py        # 在 8080 起服務
  環境變數 PORT=9090 python3 gpu_gateway.py   # 改埠
"""
import subprocess
import json
import sys
import os
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer

BASE = os.path.dirname(os.path.abspath(__file__))
DASHBOARD = os.path.join(BASE, 'gpu_dashboard.html')


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        path = parsed.path

        if path == '/' or path == '':
            self.redirect('/gpu_dashboard.html')
            return
        if path == '/gpu_dashboard.html':
            self.serve_html()
            return
        if path == '/gpu_metric.py':
            self.serve_json()
            return
        # 其他靜態檔（CSS/JS/圖）
        self.serve_static(path)

    def redirect(self, location):
        self.send_response(302)
        self.send_header('Location', location)
        self.end_headers()

    def serve_html(self):
        with open(DASHBOARD, 'rb') as f:
            body = f.read()
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def serve_json(self):
        try:
            out = subprocess.run(
                [sys.executable, os.path.join(BASE, 'gpu_metric.py')],
                capture_output=True, text=True, timeout=10
            )
            data = json.loads(out.stdout.strip())
            body = json.dumps(data).encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        except Exception as e:
            body = json.dumps({'ok': False, 'err': str(e)}).encode('utf-8')
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)

    def serve_static(self, path):
        full = os.path.join(BASE, path.lstrip('/'))
        if os.path.isfile(full):
            with open(full, 'rb') as f:
                body = f.read()
            self.send_response(200)
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, fmt, *args):
        pass


def main():
    port = int(os.environ.get('PORT', '8080'))
    server = HTTPServer(('127.0.0.1', port), Handler)
    print(f'GPU 儀表網關已在 http://127.0.0.1:{port} 啟動（/ 跳轉 /gpu_dashboard.html）')
    server.serve_forever()


if __name__ == '__main__':
    main()
