from __future__ import annotations

import argparse
import getpass
import os
from pathlib import Path

from binance_readonly.auth import AuthStore


APP_DIR = Path(__file__).resolve().parent
RUNTIME_DIR = Path(os.getenv("BSA_RUNTIME_DIR", str(APP_DIR))).resolve()
AUTH_DB_FILE = RUNTIME_DIR / "auth.db"


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Set the private dashboard login password")
    parser.add_argument("--username", default="admin", help="Private dashboard username")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    if not RUNTIME_DIR.is_dir():
        raise SystemExit(f"Runtime directory does not exist: {RUNTIME_DIR}")
    password = getpass.getpass("New dashboard password (12+ characters): ")
    confirmation = getpass.getpass("Confirm dashboard password: ")
    if password != confirmation:
        raise SystemExit("Passwords did not match. Nothing was changed.")
    try:
        AuthStore(AUTH_DB_FILE).set_password(args.username, password)
    except ValueError as exc:
        raise SystemExit(str(exc)) from None
    finally:
        password = ""
        confirmation = ""
    print("Private dashboard login was configured. Existing sessions were revoked.")


if __name__ == "__main__":
    main()
