import subprocess, os, sys

with open('/tmp/cf_token', 'r') as f:
    token = f.read().strip()

# Read account ID
acc = open('/tmp/cf_account', 'r').read().strip() if os.path.exists('/tmp/cf_account') else '274c094edb3fe89140e277525c9c5577'

env = os.environ.copy()
env['CLOUDFLARE_API_TOKEN'] = token

def deploy(name, cwd, wrangler_cfg=None):
    cmd = ['npx', 'wrangler', 'deploy']
    if wrangler_cfg:
        cmd.extend(['--config', wrangler_cfg])
    print(f"\n=== Deploying {name} ===")
    r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=60, env=env)
    out = r.stdout.strip()
    if r.returncode == 0:
        for line in out.split('\n'):
            if 'workers.dev' in line or 'Uploaded' in line:
                print(f"  {line.strip()}")
        return True
    else:
        # Print relevant error
        for line in out.split('\n'):
            if 'ERROR' in line or 'error' in line.lower():
                print(f"  ERR: {line.strip()}")
        if r.stderr:
            for line in r.stderr.split('\n')[-5:]:
                if line.strip():
                    print(f"  {line.strip()}")
        return False

# Deploy config worker
ok = deploy('addon-config-worker', '/home/rurouni/Unspooled/services/addon-config-worker')
if not ok:
    # Maybe need to delete first
    subprocess.run(['curl', '-s', '-X', 'DELETE', 
        f'https://api.cloudflare.com/client/v4/accounts/{acc}/workers/scripts/addon-config-worker',
        '-H', f'Authorization: Bearer ***    timeout=10)
    print("Deleted config worker, retrying...")
    ok = deploy('addon-config-worker', '/home/rurouni/Unspooled/services/addon-config-worker')

# Deploy auth worker  
ok2 = deploy('addon-auth-worker', '/home/rurouni/Unspooled/services/addon-config-worker', 'auth_wrangler.toml')
if not ok2:
    subprocess.run(['curl', '-s', '-X', 'DELETE',
        f'https://api.cloudflare.com/client/v4/accounts/{acc}/workers/scripts/addon-auth-worker',
        '-H', f'Authorization: Bearer ***    timeout=10)
    print("Deleted auth worker, retrying...")
    ok2 = deploy('addon-auth-worker', '/home/rurouni/Unspooled/services/addon-config-worker', 'auth_wrangler.toml')

sys.exit(0 if ok and ok2 else 1)
