#!/usr/bin/env python3
"""Monitor local disk space and send DingTalk alerts via ~/complete.py."""

import argparse
import shutil
import subprocess
import sys
import time
from pathlib import Path


DEFAULT_THRESHOLD_GIB = 5
ALERT_COUNT = 3
ALERT_DELAY_SECONDS = 1
DEFAULT_STATE_FILE = Path.home() / "codex" / "disk_space_monitor.state"


def free_bytes(path: str) -> int:
    return shutil.disk_usage(path).free


def send_alert(complete_py: Path, path: str, free: int) -> None:
    free_gib = free / (1024 ** 3)
    # complete.py uses its first argument as the message name. The .txt
    # suffix keeps its existing name[:-4] behavior intact.
    alert_name = (
        f"磁盘空间不足：{path} 仅剩 {free_gib:.2f} GiB，请尽快清理.txt"
    )

    for index in range(ALERT_COUNT):
        subprocess.run(
            [sys.executable, str(complete_py), alert_name],
            check=True,
        )
        if index < ALERT_COUNT - 1:
            time.sleep(ALERT_DELAY_SECONDS)


def monitor_once(
    path: str,
    threshold_gib: float,
    complete_py: Path,
    state_file: Path,
) -> None:
    threshold = int(threshold_gib * (1024 ** 3))
    free = free_bytes(path)
    below_threshold = free < threshold
    free_gib = free / (1024 ** 3)
    print(
        f"{path}: {free_gib:.2f} GiB free "
        f"(threshold {threshold_gib:.2f} GiB)",
        flush=True,
    )

    was_alerted = state_file.exists()
    if below_threshold and not was_alerted:
        send_alert(complete_py, path, free)
        state_file.parent.mkdir(parents=True, exist_ok=True)
        state_file.write_text("alerted\n", encoding="utf-8")
        print("Sent 3 DingTalk alerts.", flush=True)
    elif not below_threshold and was_alerted:
        state_file.unlink(missing_ok=True)
        print("Disk space recovered; alert state cleared.", flush=True)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Monitor local disk free space and send DingTalk alerts."
    )
    parser.add_argument(
        "--path",
        default="/",
        help="Filesystem path to monitor (default: /)",
    )
    parser.add_argument(
        "--threshold-gib",
        type=float,
        default=DEFAULT_THRESHOLD_GIB,
        help="Alert threshold in GiB (default: 5)",
    )
    parser.add_argument(
        "--complete-py",
        type=Path,
        default=Path.home() / "complete.py",
        help="Path to complete.py (default: ~/complete.py)",
    )
    parser.add_argument(
        "--state-file",
        type=Path,
        default=DEFAULT_STATE_FILE,
        help="Alert state file (default: ~/codex/disk_space_monitor.state)",
    )
    args = parser.parse_args()

    if args.threshold_gib <= 0:
        parser.error("--threshold-gib must be positive")
    if not args.complete_py.is_file():
        parser.error(f"complete.py not found: {args.complete_py}")

    try:
        monitor_once(
            path=args.path,
            threshold_gib=args.threshold_gib,
            complete_py=args.complete_py,
            state_file=args.state_file,
        )
    except KeyboardInterrupt:
        print("Stopped.", file=sys.stderr)
    except FileNotFoundError as exc:
        print(f"Path not found: {exc}", file=sys.stderr)
        return 1
    except subprocess.CalledProcessError as exc:
        print(f"complete.py failed with exit code {exc.returncode}", file=sys.stderr)
        return exc.returncode or 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
