#!/usr/bin/env python3
"""Generate a strong Curogram password and store it to the 0600 creds env.
NEVER prints the password. Writes/updates CUROGRAM_AGENT_PASSWORD in the env file
and a non-secret companion file with the login URL + username.
Avoids the word 'agent' in the password per task instruction."""
import os, secrets, string

CREDS = "/home/claude/.config/amd-agent/credentials.env"
LOGIN_URL = "https://app.curogram.com/login"
USERNAME = "agent@exulthealthcare.com"

# Strong: 24 chars, mixed classes, no ambiguous chars, guaranteed one of each.
alphabet = string.ascii_letters + string.digits + "!@#$%^&*-_=+"
def gen():
    while True:
        pw = "".join(secrets.choice(alphabet) for _ in range(24))
        if (any(c.islower() for c in pw) and any(c.isupper() for c in pw)
                and any(c.isdigit() for c in pw)
                and any(c in "!@#$%^&*-_=+" for c in pw)
                and "agent" not in pw.lower()):
            return pw

# Read existing lines, drop any prior CUROGRAM_AGENT_PASSWORD.
lines = []
existing_pw = None
if os.path.exists(CREDS):
    with open(CREDS) as f:
        for ln in f:
            if ln.startswith("CUROGRAM_AGENT_PASSWORD="):
                existing_pw = ln.split("=", 1)[1].strip()
                continue
            lines.append(ln.rstrip("\n"))

if existing_pw:
    pw = existing_pw  # reuse if already set (idempotent re-run)
    print("REUSED_EXISTING_PW (already stored)")
else:
    pw = gen()
    print("GENERATED_NEW_PW")

lines.append("CUROGRAM_AGENT_PASSWORD=" + pw)
lines.append("CUROGRAM_AGENT_LOGIN_URL=" + LOGIN_URL)
lines.append("CUROGRAM_AGENT_USERNAME=" + USERNAME)

with open(CREDS, "w") as f:
    f.write("\n".join(lines) + "\n")
os.chmod(CREDS, 0o600)
print("STORED -> CUROGRAM_AGENT_PASSWORD, CUROGRAM_AGENT_LOGIN_URL, CUROGRAM_AGENT_USERNAME")
print("LEN:", len(pw))  # length only, never the value
