{
	admin off
	auto_https off
	# Error logs must not retain mistyped credential URLs or request headers.
	log {
		format filter {
			wrap json
			fields {
				request delete
			}
		}
	}
}

{$PM_WEB_LISTEN::8080} {
	# This origin is intentionally HTTP-only behind a separately managed TLS edge.
	# The shipped deployment never serves demonstration routes, even for a Lab build.
	@lab path /lab /lab/*
	handle @lab {
		respond "Not Found" 404
	}

	# External MCP and its OAuth discovery/handshake are served by the Agent.
	# The public origin is deployment-pinned; local no-token access is only enabled
	# when MCP_PUBLIC_ORIGIN itself is a loopback HTTP origin.
	@mcp path /mcp /.well-known/oauth-protected-resource /.well-known/oauth-protected-resource/mcp /.well-known/oauth-authorization-server
	handle @mcp {
		reverse_proxy {$AGENT_API_UPSTREAM:agent:4325} {
			flush_interval -1
		}
	}

	@mcpOAuth path /oauth/mcp/register /oauth/mcp/authorize /oauth/mcp/approval /oauth/mcp/decision /oauth/mcp/token
	handle @mcpOAuth {
		reverse_proxy {$AGENT_API_UPSTREAM:agent:4325} {
			flush_interval -1
		}
	}

	# Agent API wins over the Agent SPA. Caddy preserves Host/Origin and upgrades WS.
	@agentApi path /agent/api /agent/api/*
	handle @agentApi {
		uri strip_prefix /agent
		reverse_proxy {$AGENT_API_UPSTREAM:agent:4325} {
			flush_interval -1
		}
	}

	@account path /pm/account /pm/account/*
	handle @account {
		root * {$PM_WEB_ROOT:/srv/pm}
		try_files {path} /index.html
		header {
			Cache-Control "no-store"
			Referrer-Policy "no-referrer"
			Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
		}
		file_server
	}

	# PM service-only proof/reconciliation must never reach the generic public API proxy.
	# Caddy's path matcher compares the decoded request path.
	@pmInternal path /api/v1/internal /api/v1/internal/*
	handle @pmInternal {
		header Cache-Control "no-store"
		respond "Not Found" 404
	}

	@api path /api /api/* /health /health/* /openapi.json
	handle @api {
		reverse_proxy {$PM_API_UPSTREAM:api:4194} {
			# Flush SSE immediately; preserve cookies, Origin, Last-Event-ID and URI.
			# PUBLIC_ORIGIN on the API must match the browser-visible origin.
			flush_interval -1
		}
	}

	handle /assets/* {
		root * {$PM_WEB_ROOT:/srv/pm}
		header Cache-Control "public, max-age=31536000, immutable"
		file_server
	}

	handle {
		root * {$PM_WEB_ROOT:/srv/pm}
		try_files {path} /index.html
		header Cache-Control "no-cache"
		file_server
	}
}
