# ETH — Tilt development environment
# Usage: cd ctrl && tilt up
# Cluster: kind (name: eth — create via ./kind-config.sh)
# Entry point: http://localhost:8050  (or http://eth.local.ar via Caddy)

allow_k8s_contexts('kind-eth')

# Hard guard: Tilt snapshots the kubectl context at startup (before parsing
# this file), so we can't switch it from here. Prefer `tilt up --context
# kind-eth` to bypass the shell's global context entirely.
if k8s_context() != 'kind-eth':
    fail("Wrong kubectl context: '%s'. Run with: tilt up --context kind-eth" % k8s_context())

local('kubectl --context kind-eth create namespace eth --dry-run=client -o yaml | kubectl --context kind-eth apply -f -')

k8s_yaml(kustomize('k8s/overlays/dev'))

# --- Images ---

docker_build(
    'eth-lambda',
    context='..',
    dockerfile='Dockerfile.lambda',
    ignore=['.git', 'def', '.venv', 'docs', '__pycache__', '.pytest_cache'],
    live_update=[
        # Whole functions/ directory — new files appear in the tester's
        # function list automatically; edits to existing files cause uvicorn
        # to drop them from the warm-cache so the next invoke is cold (the
        # `reset_modules` endpoint also lets you force it manually).
        sync('../functions', '/app/functions'),
        sync('../invoke.py', '/app/invoke.py'),
        sync('../seed.py', '/app/seed.py'),
        # runner.py change → uvicorn --reload restarts the process → all
        # function modules drop out of the cache, next invocation cold.
        sync('../runner.py', '/app/runner.py'),
    ],
)

docker_build(
    'eth-docs',
    context='..',
    dockerfile='Dockerfile.docs',
    live_update=[
        sync('../docs', '/usr/share/nginx/html'),
    ],
)

# --- Resources ---

k8s_resource('minio')
k8s_resource('lambda', resource_deps=['minio'])
k8s_resource('docs')
k8s_resource('gateway', resource_deps=['docs', 'minio'])

# Hot-reload gateway Caddy on Caddyfile edit. configMapGenerator uses
# disableNameSuffixHash so the Deployment template doesn't change → kustomize
# won't roll the pod on its own. This local_resource closes the loop.
local_resource(
    'gateway-reload',
    cmd='kubectl --context kind-eth -n eth rollout restart deployment/gateway',
    deps=['k8s/base/Caddyfile'],
    resource_deps=['gateway'],
    auto_init=False,
)

k8s_resource(
    objects=['eth:namespace', 'eth-config:configmap', 'gateway-config:configmap'],
    new_name='infra',
)
