{
	auto_https off
	# Bind the unauthenticated admin API to loopback only; nothing outside
	# the container needs it.
	admin localhost:2019
	servers {
		# Honor X-Forwarded-* from the fronting load balancer so the
		# backends see the original client scheme/host. Without this,
		# Caddy overwrites X-Forwarded-Proto with the scheme it saw
		# (http), which breaks imbi-api's per-request public URL
		# derivation for the OAuth/MCP discovery documents.
		trusted_proxies static private_ranges
	}
}

:8080 {
	@no_cache path /index.html /version.json
	header @no_cache Cache-Control "no-cache, no-store, must-revalidate"

	handle /api/* {
		reverse_proxy 127.0.0.1:8000
	}

	handle /assistant/* {
		reverse_proxy 127.0.0.1:8002
	}

	handle /docs {
		reverse_proxy 127.0.0.1:8000
	}

	handle /docs/* {
		reverse_proxy 127.0.0.1:8000
	}

	handle_path /gateway/* {
		reverse_proxy 127.0.0.1:8003
	}

	# MCP clients derive AS metadata discovery from the /mcp resource
	# URL, requesting /mcp/.well-known/oauth-authorization-server. Strip
	# the /mcp prefix and serve it from imbi-api (which registers the
	# document at the bare /.well-known path). Must precede @mcp so it
	# wins over the /mcp/* catch-all below.
	handle /mcp/.well-known/oauth-authorization-server* {
		uri strip_prefix /mcp
		reverse_proxy 127.0.0.1:8000
	}

	@mcp path /mcp /mcp/*
	handle @mcp {
		reverse_proxy 127.0.0.1:8001
	}

	# OAuth discovery: imbi-mcp serves Protected Resource Metadata
	# (RFC 9728); imbi-api serves Authorization Server metadata
	# (RFC 8414) unprefixed at the root. Both must keep their full path,
	# so use handle (not handle_path).
	handle /.well-known/oauth-protected-resource* {
		reverse_proxy 127.0.0.1:8001
	}

	handle /.well-known/oauth-authorization-server* {
		reverse_proxy 127.0.0.1:8000
	}

	handle /openapi.json {
		reverse_proxy 127.0.0.1:8000
	}

	handle /uploads/* {
		reverse_proxy 127.0.0.1:8000
	}

	@sourcemaps path *.map
	handle @sourcemaps {
		@maps_allowed expression `{env.SERVE_SOURCE_MAPS} == "true"`
		handle @maps_allowed {
			root * /srv/ui
			file_server
		}
		handle {
			respond "Not Found" 404
		}
	}

	handle {
		root * /srv/ui
		try_files {path} /index.html
		templates
		file_server
	}
}
