# NVI — Tilt development environment
# Usage: cd ctrl && tilt up
# Cluster: kind (name: nvi — create via ./kind-config.sh)
# Entry points (via system Caddy + dnsmasq; kind NodePort is 30060→host 8060):
#   http://nvi.local.ar       — UI
#   http://api.nvi.local.ar   — API
#   http://docs.nvi.local.ar  — Docs

allow_k8s_contexts('kind-nvi')

# 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-nvi` to bypass the shell's global context entirely.
if k8s_context() != 'kind-nvi':
    fail("Wrong kubectl context: '%s'. Run with: tilt up --context kind-nvi" % k8s_context())

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

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

# --- Images ---

# FastAPI — Plan / Analyses / Tools / runtime
docker_build(
    'nvi-api',
    context='..',
    dockerfile='Dockerfile.api',
    ignore=['.git', 'def', 'ui', '.claude', 'tests', '.venv', 'node_modules', '.data', 'docs'],
    live_update=[
        sync('../api', '/app/api'),
    ],
)

# Vue UI — context is project root so the framework symlink resolves
docker_build(
    'nvi-ui',
    context='..',
    dockerfile='Dockerfile.ui',
    live_update=[
        sync('../ui/app/src', '/ui/app/src'),
        sync('../ui/app/index.html', '/ui/app/index.html'),
        sync('../ui/app/vite.config.ts', '/ui/app/vite.config.ts'),
        sync('../ui/framework/src', '/ui/framework/src'),
    ],
)

# Docs — nginx serving pre-rendered HTML + Graphviz SVGs
docker_build(
    'nvi-docs',
    context='..',
    dockerfile='Dockerfile.docs',
    live_update=[
        sync('../docs', '/usr/share/nginx/html'),
    ],
)

# --- Resources ---

k8s_resource('postgres')
k8s_resource('api', resource_deps=['postgres'])
k8s_resource('ui', resource_deps=['api'])
k8s_resource('docs')
k8s_resource('gateway', resource_deps=['ui', 'api', 'docs'])

# 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-nvi -n nvi rollout restart deployment/gateway',
    deps=['k8s/base/Caddyfile'],
    resource_deps=['gateway'],
    auto_init=False,
)

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