#!/usr/bin/env python3
"""Daily Scrutiny health check — reports drive status to Telegram."""

import json
import urllib.request
import sys

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)

        # status codes: 0=unknown, 1=pass, 2=fail
        if status == 2:
            issues.append(f"🔴 *{name}* ({model}) — FAILED status")
            continue
        elif status == 1:
            healthy.append(f"✅ *{name}* ({model}) — Passed")
            continue

        # Temp warnings (HDDs >50C, SSDs >60C is concerning)
        if temp is not None:
            if "SSD" in model.upper():
                temp_str = f"🌡️ {temp}°C"
                if temp > 65:
                    issues.append(f"🔴 *{name}* ({model}) — Critical temp: {temp}°C")
                    continue
                elif temp > 55:
                    issues.append(f"⚠️ *{name}* ({model}) — High temp: {temp}°C")
                    continue
            else:
                temp_str = f"🌡️ {temp}°C"
                if temp > 55:
                    issues.append(f"🔴 *{name}* ({model}) — Critical temp: {temp}°C")
                    continue
                elif temp > 48:
                    issues.append(f"⚠️ *{name}* ({model}) — High temp: {temp}°C")
                    continue

        healthy.append(f"✅ *{name}* ({model}) — {temp_str if temp else 'N/A temp'}")

    # Build message
    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"📅 {__import__('datetime').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)
