from __future__ import annotations

import argparse
from http.server import ThreadingHTTPServer
from typing import Any


def main(handler_class: type[Any] | None = None, service: Any | None = None) -> None:
    if handler_class is None or service is None:
        from backend.application import RequestHandler, SERVICE

        handler_class = handler_class or RequestHandler
        service = service or SERVICE
    parser = argparse.ArgumentParser(description="Xiaobai stock review web application")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8765)
    args = parser.parse_args()
    server = ThreadingHTTPServer((args.host, args.port), handler_class)
    try:
        service.start_background_jobs()
        print(f"Xiaobai Review Web is running at http://{args.host}:{args.port}")
        print("Press Ctrl+C to stop.")
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        service.stop_background_jobs()
        server.server_close()
