#!/usr/bin/env python3
"""Force port 80 and redeploy so Traefik labels regenerate."""
import json, sys, urllib.request

BASE = "http://localhost:8000/api/v1"
TOKEN = "2|IqbpR94lOiexx5gXHV3BO31utUhuqwi9Y5T2lLCe1505d5d4"
APP_UUID = "bjcuhkadno0onqp2dltlfuek"

def api(method, path, data=None):
    url = BASE + path
    body = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(url, data=body, method=method)
    req.add_header("Authorization", f"Bearer {TOKEN}")
    req.add_header("Accept", "application/json")
    if body:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.status, json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode())
        except Exception:
            return e.code, e.read().decode()
    except Exception as e:
        return 0, str(e)

# Get current app
s, r = api("GET", f"/applications/{APP_UUID}")
print(f"ports_exposes: {r.get('ports_exposes')}")
print(f"build_pack: {r.get('build_pack')}")
print(f"publish_directory: {r.get('publish_directory')}")

# Set ports_exposes to 80 explicitly
data = {"ports_exposes": "80"}
s2, r2 = api("PATCH", f"/applications/{APP_UUID}", data)
print(f"PATCH ports: {s2}")
print(json.dumps(r2, indent=2))
