# src/veritell_langchain/cli.py
from __future__ import annotations

import argparse
import sys
from pathlib import Path

from veritell_langchain.onboarding import (
    default_config_path,
    provision_keys_interactive,
    read_env_provisioning,
    redact_secret,
    write_config_file,
)


def _cmd_init(args: argparse.Namespace) -> int:
    cfg_path: Path = Path(args.config_path) if args.config_path else default_config_path()

    stg, prod = read_env_provisioning()
    if (not stg.api_key) or (not prod.api_key):
        stg, prod = provision_keys_interactive(no_browser=args.no_browser)

    write_config_file(path=cfg_path, active_env="production", staging=stg, production=prod)

    print(f"Wrote config to: {cfg_path}")

    if args.print:
        print("WARNING: printing API keys can leak secrets via shell history/logs.")
        print(f"staging api_key: {stg.api_key}")
        print(f"production api_key: {prod.api_key}")
    else:
        print(f"staging api_key: {redact_secret(stg.api_key)}")
        print(f"production api_key: {redact_secret(prod.api_key)}")

    return 0


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(prog="veritell")
    sub = p.add_subparsers(dest="command", required=True)

    init_p = sub.add_parser("init", help="Provision and save Veritell API keys")
    init_p.add_argument("--config-path", dest="config_path", default=None)
    init_p.add_argument("--print", action="store_true", help="Explicitly print secrets (dangerous)")
    init_p.add_argument(
        "--no-browser",
        action="store_true",
        help="Disable browser-based auth (prompt mode only)",
    )
    init_p.set_defaults(_handler=_cmd_init)

    return p


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    ns = parser.parse_args(argv if argv is not None else sys.argv[1:])
    return int(ns._handler(ns))
