load('ext://namespace', 'namespace_create')
load('ext://restart_process',  'docker_build_with_restart')
load('ext://secret', 'secret_create_generic')
load('ext://helm_remote', 'helm_remote')

config.define_string('topolvm_backing_size')
cfg = config.parse()
# Sparse loopback file size. Sparse means this is a ceiling, not a reservation —
# 20 GiB on a fresh cluster costs ~0 bytes. Bump if your test workloads fill more.
TOPOLVM_BACKING_SIZE = cfg.get('topolvm_backing_size', '20G')

has_depot_credentials = os.path.exists('./.env.depot')

local_resource(
  'namespace',
  'kubectl apply -f k8s/manifests/namespace.yaml',
  labels=['setup'],
)

local_resource(
  'rbac',
  'kubectl apply -f k8s/manifests/rbac.yaml',
  labels=['setup'],
)


local_resource(
  'registry',
  '''
  REGISTRY_IP=$(docker inspect ctlptl-registry --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' | awk '{print $NF}')
  echo "Registry IP: $REGISTRY_IP"
  cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
  name: ctlptl-registry
  namespace: teral
spec:
  ports:
    - port: 5000
      targetPort: 5000
---
apiVersion: discovery.k8s.io/v1
kind: EndpointSlice
metadata:
  name: ctlptl-registry
  namespace: teral
  labels:
    kubernetes.io/service-name: ctlptl-registry
addressType: IPv4
endpoints:
  - addresses:
      - "$REGISTRY_IP"
ports:
  - port: 5000
EOF
  ''',
  resource_deps=['namespace'],
  labels=['setup'],
)

local_resource(
  'cilium-policies',
  'kubectl apply -f k8s/manifests/cilium-policies.yaml',
  labels=['setup'],
)

local_resource(
    'depot-credentials',
    'if [ -f ./.env.depot ]; then kubectl -n teral create secret generic depot-credentials --from-env-file=./.env.depot -o yaml --dry-run=client | kubectl apply -f -; else echo "Skipping depot-credentials (no .env.depot file)"; fi',
    resource_deps=['namespace'],
    deps=['./.env.depot'],
    labels=['setup'],
    allow_parallel=True,
)

local_resource(
    'github-credentials',
    '''if [ -f ./.env.github ] && [ -f ./.github-private-key.pem ]; then set -a && source ./.env.github && set +a && kubectl -n teral create secret generic github-credentials \
      --from-literal=TERAL_GITHUB_APP_ID="$TERAL_GITHUB_APP_ID" \
      --from-literal=TERAL_GITHUB_APP_WEBHOOK_SECRET="$TERAL_GITHUB_APP_WEBHOOK_SECRET" \
      --from-literal=NEXT_PUBLIC_GITHUB_APP_NAME="$NEXT_PUBLIC_GITHUB_APP_NAME" \
      --from-literal=TERAL_ALLOW_UNAUTHENTICATED_DEPLOYMENTS="$TERAL_ALLOW_UNAUTHENTICATED_DEPLOYMENTS" \
      --from-file=TERAL_GITHUB_PRIVATE_KEY_PEM=./.github-private-key.pem \
      -o yaml --dry-run=client | kubectl apply -f -; else echo "Skipping github-credentials (missing .env.github or .github-private-key.pem)"; fi''',
    resource_deps=['namespace'],
    deps=['./.env.github', './.github-private-key.pem'],
    labels=['setup'],
    allow_parallel=True,
)

# MySQL service
docker_build('teral/mysql:local', '..', dockerfile='./Dockerfile.mysql')
k8s_yaml('k8s/manifests/mysql.yaml')
k8s_resource('mysql', port_forwards='3306:3306', resource_deps=[], labels=['database'])

# ClickHouse service
docker_build('teral/clickhouse:local', '..', dockerfile='./Dockerfile.clickhouse')
k8s_yaml('k8s/manifests/clickhouse.yaml')
k8s_resource('clickhouse', port_forwards=['8123:8123','9000:9000'], resource_deps=[], labels=['database'])

k8s_yaml('k8s/manifests/s3.yaml')
k8s_resource('s3', port_forwards=['3902:3902', '3903:3903'], resource_deps=[], labels=['database'])

k8s_yaml('k8s/manifests/planetscale.yaml')
k8s_resource(
    'planetscale',
    port_forwards='3900:3900',
    resource_deps=['mysql'],
    labels=['database']
)

# Restate service
k8s_yaml('k8s/manifests/restate.yaml')
k8s_resource('restate', port_forwards=['8080:8080', '9070:9070'], resource_deps=[], labels=['database'])

# Prometheus Monitoring
##k8s_yaml('k8s/manifests/observability.yaml')
#k8s_resource(
#  'prometheus',
#  port_forwards='9090:9090',
#  resource_deps=['api'],
#  labels=['observability']
#)
#k8s_resource(
#  'otel-collector',
#  port_forwards='3000:3000',
#  labels=['observability']
#)

# Build Go binaries locally (auto-detect arch from minikube)
local_resource(
    'build-teral',
    'cd .. && CGO_ENABLED=0 GOOS=linux GOARCH=$(minikube ssh -- uname -m | sed "s/x86_64/amd64/" | sed "s/aarch64/arm64/" | tr -d "\\r") go build -o bin/teral .',
    deps=['../main.go', '../pkg', '../cmd', '../svc', '../gen'],
    labels=['build'],
)

# Single docker image for all Go services - k8s manifests use `args` to specify which service to run
docker_build_with_restart(
    'teral/go:latest',
    '..',
    dockerfile='./Dockerfile.tilt',
    entrypoint=['/teral'],
    only=['./bin'],
    live_update=[sync('./bin/teral', '/teral')]
)

# Vault service
k8s_yaml('k8s/manifests/vault.yaml')
k8s_resource(
  'vault',
  port_forwards='8060:8060',
  resource_deps=['s3', 'build-teral'],
  labels=['teral'],
  auto_init=True,
  trigger_mode=TRIGGER_MODE_AUTO
)

# API Service
k8s_yaml('k8s/manifests/api.yaml')
k8s_resource(
  'api',
  port_forwards='7070:7070',
  # TODO: re-add other deps
  resource_deps=['mysql', 'clickhouse', 'build-teral'],
  # resource_deps=['mysql', 'clickhouse', 'redis', 'build-teral'],
  labels=['teral'],
  auto_init=True,
  trigger_mode=TRIGGER_MODE_AUTO
)

# Ctrl service
k8s_yaml('k8s/manifests/ctrl-api.yaml')
# TODO: re-add other deps
ctrl_api_deps = ['mysql', 'clickhouse', 'restate', 'vault', 'build-teral', 'github-credentials']
if has_depot_credentials:
    ctrl_api_deps.append('depot-credentials')
k8s_resource(
  'ctrl-api',
  port_forwards='7091:7091',
  resource_deps=ctrl_api_deps,
  labels=['teral'],
  auto_init=True,
  trigger_mode=TRIGGER_MODE_AUTO
)

# Worker service (Restate workflow handlers)
k8s_yaml('k8s/manifests/ctrl-worker.yaml')
# TODO: re-add other deps
ctrl_worker_deps = ['mysql', 'clickhouse', 'restate', 'build-teral', 'github-credentials']
#ctrl_worker_deps = ['mysql', 'clickhouse', 'restate', build-teral', 'webhooks-config', 'github-credentials']
if has_depot_credentials:
    ctrl_api_deps.append('depot-credentials')
k8s_resource(
  'ctrl-worker',
  port_forwards='7092:7092',
  resource_deps=ctrl_worker_deps,
  labels=['teral'],
  auto_init=True,
  trigger_mode=TRIGGER_MODE_AUTO
)

# Krane service
k8s_yaml('k8s/manifests/krane.yaml')
k8s_resource(
  'krane',
  port_forwards='8070:8070',
  # TODO: re-add other deps
  resource_deps=['ctrl-api', 'build-teral', 'rbac', 'namespace', 'cilium-policies', 'depot-credentials'],
  # resource_deps=['ctrl-api', 'build-teral', 'rbac', 'namespace', 'sentinel', 'cilium-policies', 'build-sentinel-image', 'depot-credentials'],
  labels=['teral'],
  auto_init=True,
  trigger_mode=TRIGGER_MODE_AUTO
)