import re

with open('/etc/caddy/Caddyfile', 'r') as f:
    content = f.read()

# Add apps proxy inside hub.gen3.ai block, before the static handler
apps_block = """    handle /apps/simple-todo-list-api/* {
        uri strip_prefix /apps/simple-todo-list-api
        reverse_proxy 127.0.0.1:3074
    }

"""

# Insert before the existing "handle {" in hub.gen3.ai
if '/apps/' not in content:
    content = content.replace(
        '    # Static frontend files\n    handle {',
        apps_block + '    # Static frontend files\n    handle {'
    )
    # Also try without comment
    if '/apps/' not in content:
        # Find hub.gen3.ai block and add before last handle
        content = content.replace(
            '    handle {\n        root * /var/www/hub/dist',
            apps_block + '    handle {\n        root * /var/www/hub/dist'
        )

with open('/etc/caddy/Caddyfile', 'w') as f:
    f.write(content)

print("✅ Caddyfile patched")
