"""CLI entry: python -m web"""

from __future__ import annotations

import argparse
import signal
import sys
import threading
from pathlib import Path

from .config import load_config
from .health import start_health_thread
from .logging_setup import setup_logging
from .redis_io import WebRedis
from .server import run_server


def _path_writable(dir_path: Path) -> bool:
    try:
        dir_path.mkdir(parents=True, exist_ok=True)
        test = dir_path / ".write_test"
        test.write_text("")
        test.unlink()
        return True
    except OSError:
        return False


def main() -> None:
    parser = argparse.ArgumentParser(description="Hot tub web service")
    parser.add_argument(
        "--config",
        type=Path,
        default=Path("/etc/hot-tub/web.json"),
        help="Path to JSON config (default: /etc/hot-tub/web.json)",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="Debug logging")
    args = parser.parse_args()

    cfg_path = args.config if args.config.exists() else None
    if cfg_path is None:
        dev_example = Path(__file__).resolve().parent / "config.example.json"
        cfg_path = dev_example if dev_example.exists() else None

    cfg = load_config(cfg_path)

    if not _path_writable(cfg.log_path.parent):
        cfg.log_path = Path("/tmp/hot-tub-web.log")

    setup_logging(cfg.log_path, verbose=args.verbose)

    redis_io = WebRedis(cfg.redis_url)
    stop = threading.Event()

    def _shutdown(_signum: int, _frame: object) -> None:
        stop.set()
        sys.exit(0)

    signal.signal(signal.SIGTERM, _shutdown)
    signal.signal(signal.SIGINT, _shutdown)

    start_health_thread(redis_io, cfg, stop)
    try:
        run_server(cfg, redis_io)
    finally:
        stop.set()
        redis_io.close()


if __name__ == "__main__":
    main()
