variable "wait_on" {
  type        = any
  description = "Resources to wait on"
  default     = true
}

variable "server_ip" {
  type = string
}

variable "ssh_private_key_path" {
  type = string
}

variable "server_domain" {
  type = string
}

module "deeptutor" {
  source = "../quadlet-app"
  wait_on = var.wait_on

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  app_name = "deeptutor"
  image    = "ghcr.io/hkuds/deeptutor:latest"
  ports    = ["8001:8001", "3782:3782"]
  volumes = [
    "/opt/storage/data/deeptutor/config:/app/config:Z",
    "/opt/storage/data/deeptutor/user:/app/data/user:Z",
    "/opt/storage/data/deeptutor/knowledge_bases:/app/data/knowledge_bases:Z",
  ]

  environment = {
    # LLM Configuration (Required - set these in terraform.tfvars)
    LLM_BINDING          = "openai"
    LLM_MODEL            = "deepseek/deepseek-v3.2"
    LLM_BINDING_API_KEY  = "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"
    LLM_BINDING_HOST     = "https://openrouter.ai/api/v1"
    DISABLE_SSL_VERIFY  = "false"

    # Embedding Configuration (Required for Knowledge Base)
    EMBEDDING_BINDING       = "openai"
    EMBEDDING_MODEL         = "text-embedding-3-large"
    EMBEDDING_BINDING_API_KEY = "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"
    EMBEDDING_BINDING_HOST  = "https://openrouter.ai/api/v1"
    EMBEDDING_DIM           = "3072"
    EMBEDDING_MAX_TOKENS    = "8192"

    # TTS Configuration (Optional)
    TTS_MODEL   = ""
    TTS_API_KEY = ""
    TTS_URL     = ""
    TTS_VOICE   = "alloy"

    # Web Search Configuration (Optional)
    PERPLEXITY_API_KEY = ""

    # Logging Configuration
    RAG_TOOL_MODULE_LOG_LEVEL = "INFO"

    # Service Ports
    BACKEND_PORT  = "8001"
    FRONTEND_PORT = "3782"

    # External API URL (for browser access if different from localhost)
    NEXT_PUBLIC_API_BASE_EXTERNAL = "https://deeptutor-api.${var.server_domain}"
  }

  healthcmd = "curl -f http://localhost:8001/ || exit 1"

  haproxy_services = [
    {
      name   = "deeptutor-frontend"
      domain = "deeptutor.${var.server_domain}"
      port   = "3782"
      host   = "127.0.0.1"
      tls    = false
    },
    {
      name   = "deeptutor-api"
      domain = "deeptutor-api.${var.server_domain}"
      port   = "8001"
      host   = "127.0.0.1"
      tls    = false
    }
  ]
}

output "app_urls" {
  value = module.deeptutor.app_urls
}

output "installed" {
  value = true
  depends_on = [module.deeptutor.installed]
}
