"""
launch_agent.py — installs / removes a macOS LaunchAgent so OTP Watcher
starts automatically when you log in.

The plist is written to ~/Library/LaunchAgents/com.otpwatcher.app.plist
and loaded/unloaded via launchctl.
"""

import subprocess
import sys
from pathlib import Path

LABEL      = "com.otpwatcher.app"
PLIST_DIR  = Path.home() / "Library" / "LaunchAgents"
PLIST_PATH = PLIST_DIR / f"{LABEL}.plist"
APP_DIR    = Path(__file__).parent

_PLIST_TEMPLATE = """\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{label}</string>

    <key>ProgramArguments</key>
    <array>
        <string>{python}</string>
        <string>{script}</string>
    </array>

    <key>WorkingDirectory</key>
    <string>{work_dir}</string>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <true/>

    <key>StandardOutPath</key>
    <string>{log}</string>

    <key>StandardErrorPath</key>
    <string>{log}</string>
</dict>
</plist>
"""


def is_enabled():
    return PLIST_PATH.exists()


def enable():
    """Write the LaunchAgent plist and load it immediately."""
    plist = _PLIST_TEMPLATE.format(
        label    = LABEL,
        python   = sys.executable,
        script   = str(APP_DIR / "app.py"),
        work_dir = str(APP_DIR),
        log      = str(APP_DIR / "otp.log"),
    )
    PLIST_DIR.mkdir(parents=True, exist_ok=True)
    PLIST_PATH.write_text(plist)
    subprocess.run(["launchctl", "load", str(PLIST_PATH)], check=False)
    print("[launch_agent] Enabled — will start at next login")


def disable():
    """Unload and remove the LaunchAgent plist."""
    if PLIST_PATH.exists():
        subprocess.run(["launchctl", "unload", str(PLIST_PATH)], check=False)
        PLIST_PATH.unlink()
        print("[launch_agent] Disabled")
