import os
import subprocess
import tempfile

BACKEND_CONFIG_TEMPLATE = """
# This was automatically generated by running "datateer infra init-remote-state"
terraform {{
  backend "s3" {{
    bucket         = "datateer-terraform-remote-state-backend-{client_code}"
    dynamodb_table = "terraform-lock"
    encrypt        = true
    key            = "states/terraform.tfstate"
    profile        = "{aws_profile}"
    region         = "{aws_region}"
  }}
}}
"""


def configure_remote_state_backend(aws_profile, aws_region, client_code):
    if not os.path.exists("main.tf"):
        raise Exception(
            "Could not find file main.tf. Are you sure you are in the right directory? (<client-code>-infrastructure)"
        )
    command = ["terraform", "init", "-force-copy", "-backend=false"]
    subprocess.run(command)

    with tempfile.TemporaryDirectory() as tmp:
        backend_plan_path = os.path.join(tmp, "backend.plan")
        command = [
            "terraform",
            "plan",
            f"-out={backend_plan_path}",
            "-target=module.datateer_infrastructure.module.backend",
        ]
        subprocess.run(command)

        command = ["terraform", "apply", backend_plan_path]
        subprocess.run(command)

    f = open("main.tf", "r")
    backend_config_exists = 'backend "s3"' in f.read()
    f.close()
    if not backend_config_exists:
        backend_config = BACKEND_CONFIG_TEMPLATE.format(
            **{
                "aws_region": aws_region,
                "client_code": client_code,
                "aws_profile": aws_profile,
            }
        )
        with open("main.tf", "a") as f:
            f.write("")
            f.write(backend_config)
            f.write("")
    else:
        print("backend configuration already exists in main.tf, so not modifying it")

    command = ["terraform", "init", "-force-copy"]
    subprocess.run(command)
