session_file = os.getenv("LDW_SESSION_FILE", "")
if not session_file:
    fail("LDW_SESSION_FILE is required; start Tilt through `ldw up --ui`.")

allow_k8s_contexts("kind-ldw-dev")
update_settings(max_parallel_updates=6)

session = decode_json(read_file(session_file))

def broker_command(resource, phase):
    return [
        session["runtime_python"],
        "-m",
        "local_devops_workbench.tilt_command",
        resource["name"],
        phase,
    ]

def build_readiness_probe(spec):
    if not spec:
        return None
    timeout = spec["timeout_seconds"]
    if spec["kind"] == "http":
        return probe(
            timeout_secs=timeout,
            http_get=http_get_action(
                host=spec["host"],
                port=spec["port"],
                scheme=spec["scheme"],
                path=spec["path"],
            ),
        )
    if spec["kind"] == "tcp":
        return probe(
            timeout_secs=timeout,
            tcp_socket=tcp_socket_action(host=spec["host"], port=spec["port"]),
        )
    return probe(timeout_secs=timeout, exec=exec_action(spec["command"]))

for project in session["projects"]:
    project_environment = {}
    for name, source in project.get("environment", {}).items():
        project_environment[name] = os.getenv(source, "")
    project_environment["LDW_SESSION_FILE"] = session_file
    for resource in project["resources"]:
        resource_links = []
        for endpoint in resource["links"]:
            resource_links.append(link(endpoint["url"], endpoint["name"]))
        trigger = TRIGGER_MODE_AUTO if resource["auto_init"] else TRIGGER_MODE_MANUAL
        readiness = build_readiness_probe(resource.get("readiness_probe"))
        if resource["serve_cmd"]:
            local_resource(
                resource["name"],
                cmd=broker_command(resource, "update"),
                serve_cmd=broker_command(resource, "serve"),
                dir=resource["cwd"],
                serve_dir=resource["cwd"],
                resource_deps=resource["dependencies"],
                auto_init=resource["auto_init"],
                trigger_mode=trigger,
                links=resource_links,
                labels=[resource["group"]],
                readiness_probe=readiness,
                env=project_environment,
                serve_env=project_environment,
            )
        else:
            local_resource(
                resource["name"],
                cmd=broker_command(resource, "update"),
                dir=resource["cwd"],
                resource_deps=resource["dependencies"],
                auto_init=resource["auto_init"],
                trigger_mode=trigger,
                links=resource_links,
                labels=[resource["group"]],
                env=project_environment,
            )
