"""Terraform provider override file generation and cleanup.

Generates a ``_lws_override.tf`` file that redirects the AWS provider
endpoints to local LWS ports so ``terraform apply`` talks to LWS
instead of real AWS.
"""

from __future__ import annotations

from pathlib import Path

OVERRIDE_FILENAME = "_lws_override.tf"
MARKER_COMMENT = "# Auto-generated by LWS - do not edit. Deleted on shutdown."


def generate_override(port: int, project_dir: Path) -> Path:
    """Generate the Terraform provider override file.

    Args:
        port: The LWS base port.
        project_dir: The Terraform project root directory.

    Returns:
        Path to the generated override file.

    Raises:
        FileExistsError: If the file exists and was not generated by LWS.
    """
    override_path = project_dir / OVERRIDE_FILENAME

    if override_path.exists():
        first_line = override_path.read_text().split("\n", 1)[0]
        if first_line.strip() != MARKER_COMMENT:
            raise FileExistsError(
                f"{OVERRIDE_FILENAME} already exists and was not generated by LWS. "
                "Remove it manually or rename it before running lws dev."
            )

    content = _build_override_content(port)
    override_path.write_text(content)
    return override_path


def cleanup_override(project_dir: Path) -> None:
    """Remove the LWS-generated override file if it exists.

    Only removes the file if it contains the LWS marker comment.
    """
    override_path = project_dir / OVERRIDE_FILENAME
    if not override_path.exists():
        return

    first_line = override_path.read_text().split("\n", 1)[0]
    if first_line.strip() == MARKER_COMMENT:
        override_path.unlink()


def _build_override_content(port: int) -> str:
    """Build the HCL content for the provider override file."""
    return f"""{MARKER_COMMENT}

provider "aws" {{
  region                      = "us-east-1"
  access_key                  = "lws-local"
  secret_key                  = "lws-local"
  skip_credentials_validation = true
  skip_metadata_api_check     = true
  skip_requesting_account_id  = true
  s3_use_path_style           = true

  endpoints {{
    dynamodb         = "http://localhost:{port + 1}"
    sqs              = "http://localhost:{port + 2}"
    s3               = "http://localhost:{port + 3}"
    sns              = "http://localhost:{port + 4}"
    cloudwatchevents = "http://localhost:{port + 5}"
    stepfunctions    = "http://localhost:{port + 6}"
    cognitoidp       = "http://localhost:{port + 7}"
    apigateway       = "http://localhost:{port + 8}"
    apigatewayv2     = "http://localhost:{port + 8}"
    lambda           = "http://localhost:{port + 9}"
    iam              = "http://localhost:{port + 10}"
    sts              = "http://localhost:{port + 11}"
    ssm              = "http://localhost:{port + 12}"
    secretsmanager   = "http://localhost:{port + 13}"
    elasticache      = "http://localhost:{port + 14}"
    memorydb         = "http://localhost:{port + 15}"
    docdb            = "http://localhost:{port + 16}"
    neptune          = "http://localhost:{port + 17}"
    elasticsearch    = "http://localhost:{port + 18}"
    opensearch       = "http://localhost:{port + 19}"
    rds              = "http://localhost:{port + 20}"
    glacier          = "http://localhost:{port + 21}"
    s3tables         = "http://localhost:{port + 22}"
  }}
}}
"""
