require "kemal"
require "kubernetes"
require "prometheus"
require "db"
require "pg"

module ApiController
  VERSION = "0.1.0"

  # Initialize Prometheus metrics
  REQUESTS = Prometheus::Counter.new(:api_requests_total, "Total number of API requests")
  RESPONSE_TIME = Prometheus::Histogram.new(
    :api_response_time_seconds,
    "Response time in seconds",
    [{0.1, 0.3, 0.5, 0.7, 0.9, 1.0}]
  )

  # Configure Kubernetes client
  token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
  cert_path = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
  
  k8s_client = Kubernetes::Client.new(
    server: URI.parse("https://#{ENV["KUBERNETES_SERVICE_HOST"]? || "localhost"}:#{ENV["KUBERNETES_SERVICE_PORT"]? || "8443"}"),
    token: File.exists?(token_path) ? File.read(token_path) : "dev-token",
    certificate_file: File.exists?(cert_path) ? cert_path : nil
  )

  # Middleware for tracking metrics
  before_all do |env|
    REQUESTS.increment
    env.set "start_time", Time.monotonic
  end

  after_all do |env|
    if start_time = env.get?("start_time").try(&.as(Time::Span))
      response_time = Time.monotonic - start_time
      RESPONSE_TIME.observe(response_time.total_seconds)
    end
  end

  # Health check endpoint
  get "/health" do
    {status: "healthy", version: VERSION}.to_json
  end

  # Metrics endpoint for Prometheus
  get "/metrics" do |env|
    env.response.content_type = "text/plain"
    Prometheus::Client.collect
  end

  # API endpoints for container deployments
  get "/api/v1/deployments" do |env|
    begin
      deployments = k8s_client.list_deployments(namespace: "default")
      deployments.to_json
    rescue ex
      env.response.status_code = 500
      {error: ex.message}.to_json
    end
  end

  post "/api/v1/deployments" do |env|
    begin
      deployment = Kubernetes::Deployment.from_json(env.request.body.not_nil!)
      result = k8s_client.create_deployment(deployment, namespace: "default")
      env.response.status_code = 201
      result.to_json
    rescue ex
      env.response.status_code = 400
      {error: ex.message}.to_json
    end
  end

  delete "/api/v1/deployments/:name" do |env|
    begin
      name = env.params.url["name"]
      k8s_client.delete_deployment(name, namespace: "default")
      env.response.status_code = 204
    rescue ex
      env.response.status_code = 404
      {error: ex.message}.to_json
    end
  end

  # Start the server
  Kemal.config.port = ENV["PORT"]?.try(&.to_i) || 3000
  Kemal.run
end
