#!/usr/bin/env python3
"""
Simple HTTP server to serve the web chat interface.

Usage:
    python tools/start_webchat.py

Then open http://$WEBCHAT_HOST:$WEBCHAT_PORT in your browser.
"""

import http.server
import socketserver
import os
from pathlib import Path

try:
    from dotenv import load_dotenv
except Exception:  # pragma: no cover - optional dependency fallback
    load_dotenv = None

if load_dotenv:
    load_dotenv()

PORT = int(os.getenv("WEBCHAT_PORT", "3000"))
HOST = os.getenv("WEBCHAT_HOST", "0.0.0.0")
API_HOST = os.getenv("API_HOST", "localhost")
API_PORT = int(os.getenv("API_PORT", "8000"))
API_PROTOCOL = os.getenv("API_PROTOCOL", "http")
API_BASE_URL = os.getenv("API_BASE_URL", "")

DIRECTORY = Path(__file__).parent


def _normalize_api_host(value: str) -> str | None:
    if value in ("", "0.0.0.0", "::"):
        return None
    return value


def _build_config_js() -> str:
    api_host = _normalize_api_host(API_HOST)
    api_base = API_BASE_URL or ""
    config = [
        "window.WEBCHAT_CONFIG = {",
        f"  apiHost: {('null' if api_host is None else repr(api_host))},",
        f"  apiPort: {API_PORT},",
        f"  apiProtocol: {repr(API_PROTOCOL)},",
        f"  apiBaseUrl: {repr(api_base)},",
        "};",
    ]
    return "\n".join(config)


class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    """HTTP request handler with CORS headers."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(DIRECTORY), **kwargs)

    def end_headers(self):
        # Add CORS headers
        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')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    def do_GET(self):
        if self.path == "/config.js":
            content = _build_config_js().encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/javascript")
            self.send_header("Content-Length", str(len(content)))
            self.end_headers()
            self.wfile.write(content)
            return
        super().do_GET()


if __name__ == "__main__":
    with socketserver.TCPServer((HOST, PORT), CORSHTTPRequestHandler) as httpd:
        print(f"""
╔══════════════════════════════════════════════════════════════╗
║           Voice Analytics Hub - Web Chat Tester             ║
╚══════════════════════════════════════════════════════════════╝

🌐 Web chat interface: http://{HOST}:{PORT}/webchat.html
🔧 Backend API:          {API_BASE_URL or f"{API_PROTOCOL}://{API_HOST}:{API_PORT}"}

Убедитесь, что бэкенд запущен на порту {API_PORT}!

Нажмите Ctrl+C для остановки сервера.
""")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n\n👋 Сервер остановлен.")
