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

import os
from dataclasses import dataclass
from pathlib import Path
from typing import Optional


@dataclass(frozen=True)
class ProvisionedEnv:
    env: str
    api_key: Optional[str]
    base_url: Optional[str]


def default_config_path() -> Path:
    """
    C18-onboarding-keys: user-scoped config file.
    Windows: %APPDATA%\\veritell\\veritell.toml
    """
    appdata = os.getenv("APPDATA")
    if appdata:
        return Path(appdata) / "veritell" / "veritell.toml"
    return Path.home() / ".config" / "veritell" / "veritell.toml"


def redact_secret(secret: Optional[str]) -> str:
    if not secret:
        return "<unset>"
    if len(secret) <= 4:
        return "****"
    return f"{secret[:8]}****{secret[-4:]}"


def _prompt_secret(prompt: str) -> str:
    import getpass

    return getpass.getpass(prompt)


def read_env_provisioning() -> tuple[ProvisionedEnv, ProvisionedEnv]:
    stg_key = os.getenv("VERITELL_API_KEY_STAGING")
    prod_key = os.getenv("VERITELL_API_KEY_PRODUCTION") or os.getenv("VERITELL_API_KEY_PROD")
    stg_url = os.getenv("VERITELL_BASE_URL_STAGING") or os.getenv("VERITELL_BASE_URL_DEV")
    prod_url = os.getenv("VERITELL_BASE_URL_PRODUCTION") or os.getenv("VERITELL_BASE_URL")

    return (
        ProvisionedEnv(env="staging", api_key=stg_key, base_url=stg_url),
        ProvisionedEnv(env="production", api_key=prod_key, base_url=prod_url),
    )


def provision_keys_interactive(
    *, no_browser: bool = False
) -> tuple[ProvisionedEnv, ProvisionedEnv]:
    """
    C18: placeholder for real browser-based device-code flow.
    For now, prompt locally if env vars are missing.
    """
    stg, prod = read_env_provisioning()

    stg_key = stg.api_key or _prompt_secret("Enter VERITELL staging API key (input hidden): ")
    prod_key = prod.api_key or _prompt_secret("Enter VERITELL production API key (input hidden): ")

    return (
        ProvisionedEnv(
            env="staging", api_key=stg_key, base_url=stg.base_url or "https://api.dev.veritell.ai"
        ),
        ProvisionedEnv(
            env="production", api_key=prod_key, base_url=prod.base_url or "https://api.veritell.ai"
        ),
    )


def write_config_file(
    *,
    path: Path,
    active_env: str,
    staging: ProvisionedEnv,
    production: ProvisionedEnv,
) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)

    toml = (
        "[veritell]\n"
        f'env = "{active_env}"\n\n'
        "[veritell.environments.staging]\n"
        f'api_key = "{staging.api_key or ""}"\n'
        f'base_url = "{staging.base_url or ""}"\n\n'
        "[veritell.environments.production]\n"
        f'api_key = "{production.api_key or ""}"\n'
        f'base_url = "{production.base_url or ""}"\n'
    )
    path.write_text(toml, encoding="utf-8")
