"""CLI entry: python -m control"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from .config import load_config
from .daemon import run_loop, run_once
from .logging_setup import setup_logging


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 control daemon")
    parser.add_argument(
        "--config",
        type=Path,
        default=Path("/etc/hot-tub/control.json"),
        help="Path to JSON config (default: /etc/hot-tub/control.json)",
    )
    parser.add_argument(
        "--once",
        action="store_true",
        help="Run one evaluation cycle and exit",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="No Redis; log GPIO decisions only",
    )
    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 args.dry_run or not _path_writable(cfg.log_path.parent):
        cfg.log_path = Path("/tmp/hot-tub-control.log")
    if args.dry_run or not _path_writable(cfg.state_path.parent):
        cfg.state_path = Path("/tmp/hot-tub-control-state.json")

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

    if args.once:
        snapshot = run_once(cfg, dry_run=args.dry_run)
        print(json.dumps(snapshot, indent=2))
        return

    run_loop(cfg, dry_run=args.dry_run)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(0)
