from durable.lang import *

class Terraform:
    @staticmethod
    def recordSetForMachine(machineKey: str, terraformId: str, fqdn: str):
        return {"type": "terraform-record-set",
            "key": machineKey,
            "terraformId": terraformId,
            "fqdn": fqdn,
            "rrType": "A",
            "rrData": f"scaleway_instance_ip.{machineKey}.address",
        }

    @staticmethod
    def machine(key: str):
        return {"type": "terraform-machine",
            "key": key,
        }

    @staticmethod
    def declare_rules():
        @when_all(
            c.dns << (m.type == "dns-entry"),
            c.machine << ((m.type == "terraform-machine") & (m.key == c.dns.key)),
        )
        def onDnsEntry(c):
            terraformId = c.dns.fqdn.replace(".", "_")
            c.assert_fact(Terraform.recordSetForMachine(c.machine.key, terraformId, c.dns.fqdn))

        @when_all((m.type == "terraform-record-set"))
        def defaultTerraformRecordSet(c):
            pass

        @when_all((m.type == "machine"))
        def onDnsEntry(c):
            print(f"matched machine: {c.m}")
            c.assert_fact(Terraform.machine(c.m.key))

        @when_all((m.type == "terraform-machine"))
        def defaultTerraformMachine(c):
            print(f"matched terraform-machine: {c.m}")