"""
Generates Terraform provider configuration files that point
all google_* resources at the local gcplocal server.
"""

import os
from typing import Optional

from gcplocal.constants import (
    DEFAULT_PORT,
    DEFAULT_PROJECT,
    COMPUTE_API_PREFIX,
    STORAGE_API_PREFIX,
    IAM_API_PREFIX,
    PUBSUB_API_PREFIX,
    CRM_API_PREFIX,
    SQLADMIN_API_PREFIX,
)


def generate_provider_config(
    host: str = "localhost",
    port: int = DEFAULT_PORT,
    project: str = DEFAULT_PROJECT,
    output_path: Optional[str] = None,
) -> str:
    """
    Generate an HCL provider block pointing all endpoints at gcplocal.

    If output_path is given, writes the file there. Always returns the
    HCL string.
    """
    base = f"http://{host}:{port}"

    hcl = f'''terraform {{
  required_providers {{
    google = {{
      source  = "hashicorp/google"
      version = ">= 4.0"
    }}
  }}
}}

provider "google" {{
  project = "{project}"
  region  = "us-central1"
  zone    = "us-central1-a"

  access_token = "gcplocal-mock-token"

  compute_custom_endpoint                    = "{base}{COMPUTE_API_PREFIX}/"
  storage_custom_endpoint                    = "{base}{STORAGE_API_PREFIX}/"
  iam_custom_endpoint                        = "{base}{IAM_API_PREFIX}/"
  pubsub_custom_endpoint                     = "{base}{PUBSUB_API_PREFIX}/"
  cloud_resource_manager_custom_endpoint     = "{base}{CRM_API_PREFIX}/"
  sql_custom_endpoint                        = "{base}{SQLADMIN_API_PREFIX}/"
}}
'''

    if output_path:
        os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
        with open(output_path, "w") as f:
            f.write(hcl)

    return hcl
