#!/usr/bin/env python3
import json
import os
from datetime import UTC, datetime, timedelta


def main() -> None:
    # Get state directory from environment (provided by heartbeat runner)
    state_dir = os.environ.get("OTTO_HEARTBEAT_STATE_DIR", ".")
    state_file = os.path.join(state_dir, "monitor_state.json")

    # Load previous state
    state = {}
    if os.path.exists(state_file):
        try:
            with open(state_file, encoding="utf-8") as f:
                state = json.load(f)
        except Exception:
            pass

    # Sample check: see if we need to complain about disk space
    # (For demonstration, we just trigger every 12 hours)
    last_trigger_str = state.get("last_trigger")
    now = datetime.now(UTC)

    should_trigger = False
    if last_trigger_str:
        try:
            last_trigger = datetime.fromisoformat(last_trigger_str)
            if now - last_trigger > timedelta(hours=12):
                should_trigger = True
        except ValueError:
            should_trigger = True
    else:
        should_trigger = True

    if should_trigger:
        state["last_trigger"] = now.isoformat()
        with open(state_file, "w", encoding="utf-8") as f:
            json.dump(state, f)

        print(
            json.dumps(
                {
                    "status": "trigger",
                    "summary": "System Monitor: Daily status check",
                    "action": {
                        "type": "prompt",
                        "task": "Please run a quick system health check (disk space, memory) and summarize it.",
                    },
                }
            )
        )
    else:
        print(json.dumps({"status": "idle"}))


if __name__ == "__main__":
    main()
