#!/usr/bin/env python3
"""Usage: hello-cal-set <KEY>   Saves one calendar setting to ~/.hello/calendars.env (chmod 600). Nothing you type is shown."""
import getpass, os, sys, warnings
from pathlib import Path
KEYS = ("GCAL_MAIN_ICS", "GCAL_WORK_ICS", "ICLOUD_USER", "ICLOUD_APP_PASSWORD", "ICLOUD_CALENDAR")
HINT = {"GCAL_MAIN_ICS": "Google 'Secret address in iCal format' for your main calendar",
        "GCAL_WORK_ICS": "Google 'Secret address in iCal format' for you@example.com",
        "ICLOUD_USER": "your Apple ID email", "ICLOUD_APP_PASSWORD": "the Apple app-specific password",
        "ICLOUD_CALENDAR": "the iCloud calendar name to use (default Family)"}
key = (sys.argv[1] if len(sys.argv) > 1 else "").upper()
if key not in KEYS: sys.exit("Usage: hello-cal-set <" + "|".join(KEYS) + ">")
path = Path(os.environ.get("HELLO_CAL_ENV", str(Path.home() / ".hello" / "calendars.env")))
warnings.simplefilter("ignore")
val = getpass.getpass(f"Paste {HINT[key]} (nothing will show), then press Enter: ").strip().strip('"').strip("'")
if key == "ICLOUD_APP_PASSWORD": val = val.replace(" ", "")
if not val: sys.exit("Nothing entered, nothing saved.")
if "\n" in val: sys.exit("That had a line break in it, nothing saved.")
if key.startswith("GCAL") and not val.startswith(("https://", "webcal://")): sys.exit("That doesn't look like a calendar link (should start with https://). Nothing saved.")
if key.startswith("GCAL"): val = "https://" + val[len("webcal://"):] if val.startswith("webcal://") else val
lines = path.read_text().splitlines() if path.exists() else []
lines = [l for l in lines if not l.split("=", 1)[0].strip() == key] + [f"{key}={val}"]
old = os.umask(0o077); path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp"); tmp.write_text("\n".join(lines) + "\n"); os.chmod(tmp, 0o600); tmp.replace(path); os.umask(old)
os.chmod(path, 0o600)
print(f"Saved {key} ({len(val)} characters). Hello picks it up within 15 minutes; text 'calendar status' to check.")
