#!/usr/bin/env python3
"""
Daily Scrutiny drive health check — outputs formatted health report to stdout.

Designed for cron jobs with no_agent=True: script output is delivered verbatim.
All-clear days produce a quiet report; flagged drives show in red/orange.

Temp thresholds:
  - SSDs: normal <55°C, warm 55-65°C, critical >65°C
  - HDDs: normal <48°C, warm 48-55°C, critical >55°C
"""

import json
import sys
import urllib.request
from datetime import datetime

SCRUTINY_URL = "http://localhost:7272/api/summary"


def get_scrutiny_data():
    try:
        with urllib.request.urlopen(SCRUTINY_URL, timeout=10) as r:
            return json.loads(r.read())
    except Exception as e:
        print(f"❌ *Scrutiny Health Check Failed*\nCould not reach Scrutiny API: {e}")
        sys.exit(0)


def check_drives(data):
    devices = data.get("data", {}).get("summary", {})
    if not devices:
        print("❌ *Scrutiny Health Check*\nNo drives found in Scrutiny.")
        return

    issues = []
    healthy = []

    for wwn, info in devices.items():
        d = info.get("device", {})
        s = info.get("smart", {})

        name = d.get("device_name", "?")
        model = d.get("model_name", "Unknown")
        temp = s.get("temp")
        hours = s.get("power_on_hours", 0)
        status = d.get("device_status", 0)

        if status == 2:
            issues.append(f"🔴 *{name}* ({model}) — FAILED status")
            continue

        is_ssd = "SSD" in model.upper()
        if temp is not None:
            high_warn = 55 if is_ssd else 48
            high_crit = 65 if is_ssd else 55
            if temp > high_crit:
                issues.append(f"🔴 *{name}* ({model}) — Critical temp: {temp}°C")
                continue
            elif temp > high_warn:
                issues.append(f"⚠️ *{name}* ({model}) — High temp: {temp}°C")
                continue
            temp_str = f"🌡️ {temp}°C"
        else:
            temp_str = "N/A temp"

        healthy.append(f"✅ *{name}* ({model}) — {temp_str}")

    lines = ["📀 *Daily Drive Health Check*\n"]
    if issues:
        lines.append("*⚠️ Issues Found:*")
        lines.extend(issues)
        lines.append("")

    lines.append("*All Drives:*")
    lines.extend(healthy)
    lines.append("")
    lines.append(f"📅 {datetime.now().strftime('%b %d, %Y %I:%M %p')}")
    lines.append("🛡️ Scrutiny + Hermes")

    print("\n".join(lines))


if __name__ == "__main__":
    data = get_scrutiny_data()
    check_drives(data)
