#!/usr/bin/env python3
"""Serve l'interface Color Picker depuis un mini-serveur HTTP local."""
import http.server
import socketserver
import threading
import webbrowser
from pathlib import Path
import signal
import os

PORT = int(os.environ.get('COLOR_PICKER_PORT', '9005'))
BASE_DIR = Path(__file__).resolve().parent
SRC_DIR = BASE_DIR / 'src'

class ColorRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(BASE_DIR), **kwargs)


def main() -> None:
    with socketserver.TCPServer(('127.0.0.1', PORT), ColorRequestHandler) as httpd:
        url = f'http://127.0.0.1:{PORT}/src/index.html'
        print(f'Color Picker disponible sur {url}')
        threading.Timer(0.3, lambda: webbrowser.open(url)).start()

        def stop(signum, frame):
            print('Arrêt du serveur Color Picker...')
            httpd.shutdown()

        signal.signal(signal.SIGINT, stop)
        signal.signal(signal.SIGTERM, stop)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass


if __name__ == '__main__':
    main()
