# Copyright (c) 2025 Airbyte, Inc., all rights reserved.
"""Utility functions for the connector builder agents."""

import json
import subprocess
import sys
from contextlib import suppress
from functools import lru_cache
from pathlib import Path

from .constants import AUTO_OPEN_TRACE_URL


@lru_cache  # Hacky way to run 'just once' 🙂
def open_if_browser_available(url: str) -> None:
    """Open a URL for the user to track progress.

    Fail gracefully in the case that we don't have a browser.
    """
    if AUTO_OPEN_TRACE_URL is False:
        return

    with suppress(Exception):
        import webbrowser  # noqa: PLC0415

        webbrowser.open(url=url)


def get_secrets_dotenv(
    existing_connector_name: str | None = None,
    existing_config_name: str | None = None,
) -> Path | None:
    """Get the path to the dotenv file for the existing connector and config, if provided."""
    if existing_connector_name and existing_config_name:
        connector_secrets_dir = (
            Path.cwd().resolve() / ".secrets" / existing_connector_name / "secrets"
        )
        connector_secrets_dir.mkdir(parents=True, exist_ok=True)
        secrets_json_file = connector_secrets_dir / f"{existing_config_name}.json"
        secrets_dotenv_path = (
            connector_secrets_dir / f"{existing_connector_name}-{existing_config_name}.env"
        )
        if secrets_dotenv_path.exists():
            print(f"✅ Found dotenv: {secrets_dotenv_path}")
            return secrets_dotenv_path

        if not secrets_json_file.exists():
            print(f"🔍 Fetching secrets for connector '{existing_connector_name}'...")
            _ = subprocess.check_output(
                [
                    "uvx",
                    "airbyte-cdk[dev]",
                    "secrets",
                    "fetch",
                    str(connector_secrets_dir.parent),
                ],
                cwd=connector_secrets_dir,
            )
            if not secrets_json_file.exists():
                raise FileNotFoundError(
                    "Specified config JSON file does not exist after "
                    f"running secrets fetch: {secrets_json_file}"
                )

        secrets_dict: dict = json.loads(secrets_json_file.read_text(encoding="utf-8"))
        if not isinstance(secrets_dict, dict):
            raise ValueError(
                f"⚠️ Warning: Expected secrets JSON file to contain a dict, got: {type(secrets_dict)}",
            )
        if "credentials" in secrets_dict:
            secrets_dict = secrets_dict["credentials"]
        else:
            print(
                f"⚠️ Warning: Expected secrets JSON file to contain 'credentials' key, got keys: {list(secrets_dict.keys())}",
                file=sys.stderr,
            )

        secrets_lines = [
            "# Secrets file generated by airbyte-connector-builder",
        ]
        secrets_lines.extend(f"{key}='{value}'" for key, value in secrets_dict.items())
        secrets_dotenv_path.write_text("\n".join(secrets_lines), encoding="utf-8")
        print(
            f"✅ Found secrets in '{secrets_json_file}' and wrote to dotenv: {secrets_dotenv_path}"
        )
        return secrets_dotenv_path

    return None
