#!/usr/bin/env python3
"""
Updater Upload Server — 集成在 drone-task-manager 内的独立 HTTP 上传服务
原样移植自 lidar_ws/scripts/updater/upload-server.py
监听 8080 端口，保存到 ~/updater，供外部前端程序上传使用
"""

import os
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from typing import Optional
import urllib.parse

UPLOAD_DIR = Path("~/updater").expanduser().resolve()
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)


class _UploadHandler(BaseHTTPRequestHandler):
    """原样复制 upload-server.py 的 Handler 逻辑"""

    def do_POST(self):
        path = urllib.parse.urlparse(self.path).path
        filename = os.path.basename(path) or "update.zip"
        os.makedirs(UPLOAD_DIR, exist_ok=True)
        dest = os.path.join(UPLOAD_DIR, filename)
        with open(dest, "wb") as f:
            f.write(self.rfile.read(int(self.headers.get("Content-Length", 0))))
        self.send_response(204)
        self.end_headers()

    def do_PUT(self):
        self.do_POST()

    def log_message(self, fmt, *args):
        # 静默日志，避免污染主服务 stdout
        pass


class UpdaterServer:
    """后台 HTTP 上传服务"""

    def __init__(self, port: int = 8080):
        self.port = port
        self._server: Optional[HTTPServer] = None
        self._thread: Optional[threading.Thread] = None

    def start(self) -> None:
        self._server = HTTPServer(("", self.port), _UploadHandler)
        self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
        self._thread.start()

    def stop(self) -> None:
        if self._server:
            self._server.shutdown()
            self._server.server_close()
