#!/usr/bin/env python3
import json
import os
import shutil
import subprocess
import sys
from datetime import datetime

ICON = "Hypr"

def run_json(cmd):
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip()
    except (FileNotFoundError, subprocess.CalledProcessError):
        return None
    if not out:
        return None
    try:
        return json.loads(out)
    except json.JSONDecodeError:
        return None

def run_text(cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip()
    except (FileNotFoundError, subprocess.CalledProcessError):
        return ""

hypr_info = {}
if shutil.which("hyprsysteminfo"):
    proc = subprocess.run(["hyprsysteminfo", "--json"], capture_output=True, text=True)
    if proc.returncode == 0 and proc.stdout.strip():
        try:
            hypr_info = json.loads(proc.stdout)
        except json.JSONDecodeError:
            hypr_info = {}

active_window = run_json(["hyprctl", "-j", "activewindow"]) or {}
monitors = run_json(["hyprctl", "-j", "monitors"]) or []
clients = run_json(["hyprctl", "-j", "clients"]) or []

focused_monitor = next((m for m in monitors if m.get("focused")), {})
monitor_name = focused_monitor.get("name") or active_window.get("monitor") or "?"
workspace = ""
ws_data = active_window.get("workspace") or focused_monitor.get("activeWorkspace")
if isinstance(ws_data, dict):
    workspace = ws_data.get("name") or ""
active_title = active_window.get("title") or active_window.get("class") or ""
layout = focused_monitor.get("layout") or ""
windows_on_monitor = sum(1 for c in clients if c.get("monitor") == monitor_name)

hypr_version = ""
if hypr_info:
    for key in ("Hyprland", "hyprland"):
        section = hypr_info.get(key)
        if isinstance(section, dict):
            hypr_version = section.get("version") or section.get("git") or ""
            if hypr_version:
                break

uptime = run_text(["uptime", "-p"]).replace("up ", "")

text_parts = ["󰣇", monitor_name]
if workspace:
    text_parts.append(f"[{workspace}]")
text = " ".join(part for part in text_parts if part)

tooltip_lines = []
if hypr_version:
    tooltip_lines.append(f"Hyprland: {hypr_version}")
if layout:
    tooltip_lines.append(f"Layout: {layout}")
if workspace:
    tooltip_lines.append(f"Workspace: {workspace}")
if active_title:
    tooltip_lines.append(f"Window: {active_title}")
if uptime:
    tooltip_lines.append(f"System uptime: {uptime}")
if windows_on_monitor:
    tooltip_lines.append(f"Windows on monitor: {windows_on_monitor}")
if not tooltip_lines:
    tooltip_lines.append("Hyprland ready")

print(json.dumps({
    "text": text,
    "tooltip": "\n".join(tooltip_lines),
    "class": ["hypr", f"workspace-{workspace}" if workspace else "hypr-no-ws"]
}))
