"""CLI entry: python -m temp"""

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 temperature daemon")
    parser.add_argument(
        "--config",
        type=Path,
        default=Path("/etc/hot-tub/temp.json"),
        help="Path to JSON config (default: /etc/hot-tub/temp.json)",
    )
    parser.add_argument(
        "--once",
        action="store_true",
        help="Read once, publish/log once, exit",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="No Redis; log/print only",
    )
    parser.add_argument(
        "--setup",
        action="store_true",
        help="Enable setup_mode for this run (probe teach-in)",
    )
    parser.add_argument(
        "--devices-path",
        type=Path,
        default=None,
        help="Override 1-Wire devices path from config",
    )
    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 and not args.config.exists():
        # Fall back to example next to package for dev
        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.setup:
        cfg.setup_mode = True
    if args.devices_path is not None:
        cfg.devices_path = args.devices_path

    if args.dry_run or not _path_writable(cfg.log_path.parent):
        cfg.log_path = Path("/tmp/hot-tub-temp.log")
    if args.dry_run or not _path_writable(cfg.probe_map_path.parent):
        cfg.probe_map_path = Path("/tmp/hot-tub-temp-probes.json")

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

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

    run_loop(cfg, dry_run=args.dry_run)


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