#!/usr/bin/env python3
"""
Securely store a login in the macOS login keychain, where an auto_login_*.py
script can read it via `security find-internet-password`. The password is
entered at a hidden prompt (getpass): it is never echoed to the screen, never
written to shell history, and never printed by this script. It is passed
straight to the macOS `security` tool and then dropped.

Generalised 2026-08-25 from the original Cazana-only version (setup_cazana_
credential.py) so the same, once-proven-safe flow covers every platform an
auto login script exists for, rather than a near duplicate script per site.

Run it with the project's Python, naming which site:
    ~/BidBrain/.venv/bin/python setup_credential.py cazana
    ~/BidBrain/.venv/bin/python setup_credential.py carwow
    ~/BidBrain/.venv/bin/python setup_credential.py motorway
    ~/BidBrain/.venv/bin/python setup_credential.py motorway_accounts
    ~/BidBrain/.venv/bin/python setup_credential.py dealerkit
    ~/BidBrain/.venv/bin/python setup_credential.py auction4cars
    ~/BidBrain/.venv/bin/python setup_credential.py dealerauction
    ~/BidBrain/.venv/bin/python setup_credential.py lecapital

Enter the login email, then the password (the password stays hidden as you
type or paste). When it says "Stored", you are done, close the window.
"""

import getpass
import subprocess
import sys
from urllib.parse import urlparse

# The real internet password "server" each site's own credential is looked
# up under, matching exactly what each auto_login_<site>.py script's own
# _keychain_lookup(SERVER) reads. Add a new site here, and its own
# auto_login_<site>.py, together.
SITES = {
    "cazana": "trade.percayso-vehicle-intelligence.co.uk",
    "carwow": "dealers.carwow.co.uk",
    "motorway": "pro.motorway.co.uk",
    # Right Drive's second Motorway account, accounts@rightdrive.co.uk
    # (Mark 2026-08-27), used only to receive watchlist star syncs
    # alongside the primary account, real purchasing there needs its own
    # SMS 2FA so stays a person's job. A real macOS keychain "server" is
    # just a lookup key, not a resolvable hostname, so this deliberately
    # distinct string (never the real "pro.motorway.co.uk", which is
    # already the primary account's own entry) is what keeps the two
    # logins from colliding when looked up.
    "motorway_accounts": "pro.motorway.co.uk.accounts",
    "auction4cars": "www.auction4cars.com",
    "dealerauction": "portal.autotrader.co.uk",
    "lecapital": "stocktrak.lecapital.co.uk",
}


def _dealerkit_server():
    """DealerKit's own hostname is dealer specific (a different tenant
    subdomain per dealership, see dealer_config.py), so it cannot be a
    fixed entry in SITES the way the others are, read it fresh instead."""
    import dealer_config
    base = getattr(dealer_config, "DEALERKIT_BASE_URL", "")
    if not base:
        return None
    return urlparse(base).netloc or None


def main():
    if len(sys.argv) != 2 or (sys.argv[1] not in SITES and sys.argv[1] != "dealerkit"):
        print(f"Usage: setup_credential.py <site>, one of: {', '.join(list(SITES) + ['dealerkit'])}")
        return 1
    site = sys.argv[1]
    if site == "dealerkit":
        server = _dealerkit_server()
        if not server:
            print("dealer_config.DEALERKIT_BASE_URL is not set, nothing to store a login for.")
            return 1
    else:
        server = SITES[site]

    label = {"motorway_accounts": "Motorway (accounts@rightdrive.co.uk)"}.get(site, site.title())
    email = input(f"{label} login email: ").strip()
    if not email:
        print("No email entered. Nothing stored.")
        return 1
    pw = getpass.getpass(f"{label} password (hidden, just type or paste then press Return): ")
    if not pw:
        print("No password entered. Nothing stored.")
        return 1
    result = subprocess.run(
        ["security", "add-internet-password", "-U",
         "-s", server, "-a", email, "-w", pw],
        capture_output=True, text=True,
    )
    pw = None  # dropped as soon as it is no longer needed
    if result.returncode == 0:
        print("Stored. You can close this window now.")
        return 0
    print("Could not store it:", (result.stderr or result.stdout).strip())
    return 1


if __name__ == "__main__":
    sys.exit(main())
