#!/bin/bash
set -e

# Generate redtag-prod CircleCI configs for all 35 services
# Usage: bash scripts/generate-redtag-prod.sh

BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
TMPL_DIR="${BASE_DIR}/scripts/redtag-prod-templates"
OUT_DIR="${BASE_DIR}/redtag-prod"

# Service definitions: SERVICE_NAME|NAMESPACE|ECR_NAME|REPO_NAME|TECH
# ECR_NAME = the Docker image name (usually same as repo name for shared-image services)
# TECH: node|php|php-webpack|php70|php73
SERVICES=(
  # booking-path family (shared image from tbi-rlv-booking-path repo)
  "tbi-rlv-booking-path|redtag|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-rlv-sales-agent-booking-path|redtag|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-rlv-market-booking-path|redtag|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-rlv-affiliate-booking-path|redtag|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-itravel-booking-path|itravel|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-sunquest-booking-path|sunquest|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-his-traveljapan-booking-path|his|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"
  "tbi-flights-booking-path|flightsca|tbi-rlv-booking-path|tbi-rlv-booking-path|php-webpack"

  # dynamic-path family (shared image from tbi-rlv-dynamic-path repo)
  "tbi-rlv-dynamic|redtag|tbi-rlv-dynamic-path|tbi-rlv-dynamic-path|php-webpack"
  "tbi-itravel-dynamic-path|itravel|tbi-rlv-dynamic-path|tbi-rlv-dynamic-path|php-webpack"
  "tbi-sunquest-dynamic-path|sunquest|tbi-rlv-dynamic-path|tbi-rlv-dynamic-path|php-webpack"
  "tbi-his-traveljapan-dynamic-path|his|tbi-rlv-dynamic-path|tbi-rlv-dynamic-path|php-webpack"

  # admin-redlabel family (shared image from tbi-admin-redlabel-ca repo)
  "tbi-admin-redlabel-ca|itravel|tbi-admin-redlabel-ca|tbi-admin-redlabel-ca|php70"
  "tbi-admin-redlabel-cron|cronjobs|tbi-admin-redlabel-ca|tbi-admin-redlabel-ca|php70"
  "tbi-admin-redlabel-cron-2|cronjobs|tbi-admin-redlabel-ca|tbi-admin-redlabel-ca|php70"
  "tbi-admin-redlabel-cron-3|cronjobs|tbi-admin-redlabel-ca|tbi-admin-redlabel-ca|php70"

  # itravel2000 family (shared image from tbi-itravel2000-com repo)
  "tbi-itravel2000-com|itravel|tbi-itravel2000-com|tbi-itravel2000-com|php70"
  "tbi-itravel2000-cron|cronjobs|tbi-itravel2000-com|tbi-itravel2000-com|php70"
  "tbi-itravel2000-cron-2|cronjobs|tbi-itravel2000-com|tbi-itravel2000-com|php70"
  "tbi-itravel2000-cron-3|cronjobs|tbi-itravel2000-com|tbi-itravel2000-com|php70"
  "tbi-itravel2000-cron-4|cronjobs|tbi-itravel2000-com|tbi-itravel2000-com|php70"

  # Single-service repos
  "tbi-redtag-cms|redtag|tbi-redtag-cms|tbi-redtag-cms|php"
  "tbi-rlv-attraction-frontend|redtag|tbi-rlv-attraction-frontend|tbi-rlv-attraction-frontend|node"
  "tbi-rlv-frontend-service|redtag|tbi-rlv-frontend-service|tbi-rlv-frontend-service|node"
  "tbi-rlv-giftcard-service|redtag|tbi-rlv-giftcard-service|tbi-rlv-giftcard-service|node"
  "tbi-rlv-hotel-content-service|redtag|tbi-rlv-hotel-content-service|tbi-rlv-hotel-content-service|php"
  "tbi-rlv-insurance-service|redtag|tbi-rlv-insurance-service|tbi-rlv-insurance-service|php"
  "tbi-rlv-attraction-bff-service|redtag|tbi-rlv-attraction-bff-service|tbi-rlv-attraction-bff-service|node"
  "tbi-rlv-petro-points-service|redtag|tbi-rlv-petro-points-service|tbi-rlv-petro-points-service|node"
  "tbi-rlv-vacations-bff-service|redtag|tbi-rlv-vacations-bff-service|tbi-rlv-vacations-bff-service|node"
  "tbi-sunquest-ca|sunquest|tbi-sunquest-ca|tbi-sunquest-ca|php73"
  "tbi-his-traveljapan-com|his|tbi-his-traveljapan-com|tbi-his-traveljapan-com|php73"
  "tbi-flights-ca|flightsca|tbi-flights-ca|tbi-flights-ca|php73"
  "tbi-travelexperts-ca|travelexperts|tbi-travelexperts-ca|tbi-travelexperts-ca|php"
  "tbi-travelexperts-redtag-ca|travelexperts|tbi-travelexperts-redtag-ca|tbi-travelexperts-redtag-ca|php"
)

# Tech-specific settings for CircleCI lint-and-test job
stamp_template() {
  local tmpl="$1"
  local svc="$2"
  local ns="$3"
  local ecr="$4"
  local repo="$5"
  local tech="$6"

  local lint_image lock_file install_cmd cache_path lint_cmd test_cmd build_cmd
  case "$tech" in
    node)
      lint_image="cimg/node:20.4"
      lock_file="package-lock.json"
      install_cmd="npm ci"
      cache_path="node_modules"
      lint_cmd="npm run lint || echo Linting completed with warnings"
      test_cmd="npm run test || echo Tests completed"
      build_cmd="npm run build"
      ;;
    *)
      lint_image="cimg/php:8.0"
      lock_file="composer.lock"
      install_cmd="composer install --no-interaction"
      cache_path="vendor"
      lint_cmd="echo PHP linting skipped"
      test_cmd="echo PHP tests skipped"
      build_cmd="echo Build validation skipped"
      ;;
  esac

  python3 -c "
import sys
with open('$tmpl') as f:
    content = f.read()
replacements = {
    '__SERVICE_NAME__': '$svc',
    '__NAMESPACE__': '$ns',
    '__ECR_NAME__': '$ecr',
    '__REPO_NAME__': '$repo',
    '__LINT_IMAGE__': '$lint_image',
    '__LOCK_FILE__': '$lock_file',
    '__INSTALL_CMD__': '$install_cmd',
    '__CACHE_PATH__': '$cache_path',
    '__LINT_CMD__': '$lint_cmd',
    '__TEST_CMD__': '$test_cmd',
    '__BUILD_CMD__': '$build_cmd',
}
for k, v in replacements.items():
    content = content.replace(k, v)
print(content, end='')
"
}

echo "Generating redtag-prod configs for ${#SERVICES[@]} services..."

for entry in "${SERVICES[@]}"; do
  IFS='|' read -r svc ns ecr repo tech <<< "$entry"
  svc_dir="${OUT_DIR}/${svc}"

  echo "  → ${svc} (${ns}, ${tech})"

  # Create directory structure
  mkdir -p "${svc_dir}/.circleci"
  mkdir -p "${svc_dir}/docker"
  mkdir -p "${svc_dir}/scripts"
  mkdir -p "${svc_dir}/charts/${svc}/templates"
  mkdir -p "${svc_dir}/.github/workflows"

  # Stamp templates
  stamp_template "${TMPL_DIR}/config.yml.tmpl" "$svc" "$ns" "$ecr" "$repo" "$tech" > "${svc_dir}/.circleci/config.yml"
  stamp_template "${TMPL_DIR}/deploy-services.sh.tmpl" "$svc" "$ns" "$ecr" "$repo" "$tech" > "${svc_dir}/scripts/deploy-services.sh"
  stamp_template "${TMPL_DIR}/setup-kubectl.sh.tmpl" "$svc" "$ns" "$ecr" "$repo" "$tech" > "${svc_dir}/scripts/setup-kubectl.sh"
  stamp_template "${TMPL_DIR}/manage-secrets.yml.tmpl" "$svc" "$ns" "$ecr" "$repo" "$tech" > "${svc_dir}/.github/workflows/manage-secrets.yml"
  stamp_template "${TMPL_DIR}/Chart.yaml.tmpl" "$svc" "$ns" "$ecr" "$repo" "$tech" > "${svc_dir}/charts/${svc}/Chart.yaml"

  chmod +x "${svc_dir}/scripts/"*.sh

  # Chart values.yaml (empty defaults)
  cat > "${svc_dir}/charts/${svc}/values.yaml" << 'EOF'
# Default values - actual values from tbi-environments
EOF

  # Chart templates - deployment.yaml
  cat > "${svc_dir}/charts/${svc}/templates/deployment.yaml" << 'TMPL'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
    group: {{ .Values.group }}
spec:
  replicas: {{ .Values.replicas }}
  selector:
    matchLabels:
      app: {{ .Values.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
        group: {{ .Values.group }}
    spec:
      containers:
      - name: web
        image: {{ .Values.image }}
        volumeMounts:
          - name: dotenv
            mountPath: /usr/src/app/.env
            subPath: .env.{{ .Values.node_env }}
        env:
        - name: NODE_ENV
          value: {{ .Values.node_env }}
        imagePullPolicy: Always
        ports:
        - containerPort: {{ .Values.targetPort }}
        resources:
          requests:
            memory: "256Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"
      volumes:
        - name: dotenv
          secret:
            secretName: {{ .Values.name }}-secrets
            items:
              - key: dotenv
                path: .env.{{ .Values.node_env }}
TMPL

  # service.yaml
  cat > "${svc_dir}/charts/${svc}/templates/service.yaml" << 'TMPL'
kind: Service
apiVersion: v1
metadata:
  namespace: {{ .Release.Namespace }}
  name: {{ .Values.name }}
spec:
  type: {{ .Values.service_type }}
  ports:
  - name: http
    port: {{ .Values.port }}
    targetPort: {{ .Values.targetPort }}
    protocol: TCP
  selector:
    app: {{ .Values.name }}
TMPL

  # ingress.yaml
  cat > "${svc_dir}/charts/${svc}/templates/ingress.yaml" << 'TMPL'
{{- if .Values.ingress_enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ .Values.name }}-ingress
  annotations:
    kubernetes.io/ingress.class: {{ .Values.ingress_type | default "nginx" }}
    ingress.kubernetes.io/ssl-redirect: "true"
    {{- if eq .Values.ingress_type "nginx" }}
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "120"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "120"
    {{- else if eq .Values.ingress_type "internal-nginx" }}
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "120"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "120"
    {{- end }}
    {{- if eq .Values.cert_manager_enabled "true" }}
    cert-manager.io/cluster-issuer: letsencrypt-prod
    {{- end }}
spec:
  {{- if eq .Values.cert_manager_enabled "true" }}
  tls:
  - hosts:
    - {{ .Values.hostName }}
    secretName: {{ .Values.name }}-tls
  {{- end }}
  rules:
  - host: {{ .Values.hostName }}
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: {{ .Values.name }}
            port:
              number: {{ .Values.port | default 80 }}
{{- end }}
TMPL

  # hpa.yaml
  cat > "${svc_dir}/charts/${svc}/templates/hpa.yaml" << 'TMPL'
{{- if .Values.autoscaling }}
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name }}
  minReplicas: {{ .Values.autoscaling.minReplicas | default 1 }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas | default 3 }}
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage | default 70 }}
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage | default 80 }}
{{- end }}
{{- end }}
TMPL

  # pdb.yaml
  cat > "${svc_dir}/charts/${svc}/templates/pdb.yaml" << 'TMPL'
{{- if .Values.podDisruptionBudget }}
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: {{ .Values.name }}
spec:
  minAvailable: {{ .Values.podDisruptionBudget.minAvailable | default 1 }}
  selector:
    matchLabels:
      app: {{ .Values.name }}
{{- end }}
{{- end }}
TMPL

  # secrets.yaml
  cat > "${svc_dir}/charts/${svc}/templates/secrets.yaml" << 'TMPL'
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Values.name }}-secrets
type: Opaque
data:
  dotenv: "{{ .Values.configs.dotenv | b64enc }}"
TMPL

  # Dockerfile - copy from app repo's existing Dockerfile
  app_repo_dir="${HOME}/Desktop/git-code/tbi-code/${repo}"
  if [ -f "${app_repo_dir}/Dockerfile" ]; then
    cp "${app_repo_dir}/Dockerfile" "${svc_dir}/docker/Dockerfile"
  else
    echo "    WARNING: No Dockerfile found in ${repo}, creating placeholder"
    echo "# TODO: Copy Dockerfile from ${repo} app repo" > "${svc_dir}/docker/Dockerfile"
  fi

  # README.md
  cat > "${svc_dir}/README.md" << EOF
# ${svc}

CircleCI pipeline configuration for ${svc} (redtag-prod).

## Pipeline

\`\`\`
lint-and-test → approve-build → build-and-push → approve-deploy → deploy
\`\`\`

- **Namespace**: ${ns}
- **Cluster**: redtag-prod
- **S3 Bucket**: tbi-charts-prod
- **Branch**: master only
- **ECR Image**: ${ecr}
- **Source Repo**: ${repo}

## Files

- \`.circleci/config.yml\` - Pipeline definition
- \`docker/Dockerfile\` - Docker build
- \`scripts/deploy-services.sh\` - Deployment automation
- \`scripts/setup-kubectl.sh\` - kubectl/helm setup
- \`charts/${svc}/\` - Helm chart
- \`.github/workflows/manage-secrets.yml\` - Secrets management
EOF

done

echo ""
echo "✅ Generated configs for ${#SERVICES[@]} services in ${OUT_DIR}/"
echo ""
echo "Summary:"
ls -d ${OUT_DIR}/tbi-* | wc -l | xargs -I{} echo "  Total service directories: {}"
find ${OUT_DIR}/tbi-*/  -name "*.yml" -o -name "*.yaml" -o -name "*.sh" -o -name "Dockerfile" -o -name "*.md" | wc -l | xargs -I{} echo "  Total files created: {}"
