#!/usr/bin/env python

import sys
import subprocess
import json

if __name__ == "__main__":
    try:
        result = subprocess.run(
            ['hyprctl', '-j', 'monitors'],
            capture_output=True, text=True, check=True
        )
        monitors = json.loads(result.stdout)
        monitor_names = []
        for monitor in monitors:
            if 'name' in monitor:
                monitor_names.append(monitor['name'])
        if "DP-2" in monitor_names:
            result = subprocess.run(
                ["hyprctl", "keyword", "monitor", "DP-2,disable"],
                capture_output=True, text=True, check=True
            )
            if result.returncode != 0:
                print("Failed to disable monitor Virtual-1", file=sys.stderr)
                sys.exit(1)
            else:
                result = subprocess.run(
                ["hyprctl", "keyword", "monitor", "eDP-1,3840x2160@60,0x0,1"],
                capture_output=True, text=True)
                if result.returncode != 0:
                    print("Failed to open laptop display", file=sys.stderr)
                    sys.exit(1)
        else:
            result = subprocess.run(
                ["hyprctl", "keyword", "monitor",
                 "DP-2, 2560x1080@74.99,0x0,1"],
                capture_output=True, text=True, check=True
            )
            if result.returncode != 0:
                print("Failed to set open DP-2", file=sys.stderr)
                sys.exit(1)
            else:
                result = subprocess.run(
                    ["hyprctl", "keyword", "monitor", "eDP-1,disable"],
                    capture_output=True, text=True, check=True
                )
            if result.returncode != 0:
                print("Failed to disable Laptop display",
                      file=sys.stderr)
                sys.exit(1)
            
    except subprocess.CalledProcessError as e:
        print(f"Error executing hyprctl: {e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}", file=sys.stderr)
        sys.exit(1)
