# 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 -')

# --load-restrictor=LoadRestrictionsNone: secretGenerator reads ../../../.env
# (repo root), which kustomize otherwise refuses for security. Safe here —
# it's our own repo, the path is explicit, and the only reachable file is .env.
k8s_yaml(kustomize('k8s/overlays/dev', flags=['--load-restrictor=LoadRestrictionsNone']))

# --- 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', 'ctrl/seed/data', 'api/evals/data',
    ],
    live_update=[
        sync('../api', '/app/api'),
        sync('./seed', '/app/seed'),
    ],
)

# Vue UI — context is project root so the framework dir is in scope.
# No live_update: the image is multi-stage (vite build → static dist served
# by nginx), so source changes require a full image rebuild.
docker_build(
    'nvi-ui',
    context='..',
    dockerfile='Dockerfile.ui',
)

# 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')
# In-cluster Caddy reverse proxy: owns the single NodePort (30060) and routes by
# Host header to ui / api / docs. The host's dnsmasq + system Caddy forward
# *.local.ar to this NodePort — gateway is this cluster's ingress, not the
# multi-cluster host routing.
# NOTE: editing k8s/base/Caddyfile won't roll the pod on its own
# (disableNameSuffixHash keeps the configMap name stable). Apply Caddyfile edits
# with: kubectl --context kind-nvi -n nvi rollout restart deployment/gateway
k8s_resource('gateway', resource_deps=['ui', 'api', 'docs'])

# Group infra objects (namespace, configmaps, the .env-backed secret).
k8s_resource(
    objects=[
        'nvi:namespace',
        'nvi-config:configmap',
        'gateway-config:configmap',
        'nvi-secrets:secret',
    ],
    new_name='infra',
)
