job "mothership-bot-[[BOT_ID]]" {
  region      = "[[REGION]]"
  datacenters = ["[[DATACENTER]]"]
  type        = "service"

  update {
    max_parallel     = 1
    min_healthy_time = "10s"
    healthy_deadline = "3m"
    auto_revert      = true
  }

  group "bot" {
    count = 1

    restart {
      attempts = 3
      interval = "5m"
      delay    = "15s"
      mode     = "fail"
    }

    network {
      # Uncomment if using webhooks
      # port "webhook" {
      #   to = 3000
      # }
    }

    # Volume for bot code (if using host volumes)
    volume "bot-code" {
      type      = "host"
      read_only = true
      source    = "mothership-bots"
    }

    task "bot" {
      driver = "docker"

      config {
        image      = "[[DOCKER_IMAGE]]"
        force_pull = true

        # Mount bot code volume
        mount {
          type     = "volume"
          target   = "/app/bots/[[BOT_ID]]"
          source   = "bot-code"
          readonly = true
        }
      }

      # Mount the volume
      volume_mount {
        volume      = "bot-code"
        destination = "/app/bots"
        read_only   = true
      }

      env {
        BOT_ID             = "[[BOT_ID]]"
        TELEGRAM_BOT_TOKEN = "[[BOT_TOKEN]]"
        BOT_PATH           = "/app/bots/[[BOT_ID]]"
        NODE_ENV           = "production"
        PYTHONUNBUFFERED   = "1"
      }

      # Firebase configuration from Vault
      template {
        data = <<EOF
{{- if keyExists "mothership/firebase/project_id" }}
FIREBASE_PROJECT_ID="{{ key "mothership/firebase/project_id" }}"
FIREBASE_CLIENT_EMAIL="{{ key "mothership/firebase/client_email" }}"
FIREBASE_PRIVATE_KEY="{{ key "mothership/firebase/private_key" }}"
{{- end }}
{{- range $key, $value := secrets "secret/data/mothership/bots/[[BOT_ID]]" }}
{{ $key }}="{{ $value }}"
{{- end }}
EOF
        destination = "secrets/bot.env"
        env         = true
      }

      resources {
        cpu    = [[CPU]]
        memory = [[MEMORY]]
      }

      service {
        name = "mothership-bot-[[BOT_ID]]"

        tags = [
          "bot",
          "telegram",
          "mothership",
          "bot-id-[[BOT_ID]]",
          "bot-type-[[BOT_TYPE]]"
        ]

        check {
          type     = "script"
          name     = "bot_running"
          command  = "/bin/sh"
          args     = ["-c", "pgrep -f '(node|python)' || exit 1"]
          interval = "30s"
          timeout  = "5s"
        }

        # Meta for service discovery
        meta {
          bot_id   = "[[BOT_ID]]"
          bot_type = "[[BOT_TYPE]]"
        }
      }

      logs {
        max_files     = 5
        max_file_size = 10
      }

      kill_timeout = "30s"
      kill_signal  = "SIGTERM"
    }

    ephemeral_disk {
      size = 300
    }
  }

  meta {
    bot_id         = "[[BOT_ID]]"
    bot_type       = "[[BOT_TYPE]]"
    deployed_at    = "[[DEPLOYED_AT]]"
    deployed_by    = "[[DEPLOYED_BY]]"
    mothership_ver = "[[VERSION]]"
  }
}
