"""Real Gitea 1.24.7 fixture for the linked PR scenario.
Run in an empty scratch directory with Docker; install gt 2.1.0 here as ./gt.
Exports needed for scenarios: GITEA_CLI_CONFIG_DIR=<this directory>/gt-config,
T3_SCENARIO_INHERIT_ENV=GITEA_CLI_CONFIG_DIR, T3CODE_DEV_SEED=0.
Stop and remove the two named containers after the comparison.
"""
import base64, json, pathlib, secrets, subprocess, time, urllib.request
root = pathlib.Path.cwd()
def run(*args, **kw):
    return subprocess.run(args, check=True, **kw)
(root / 'nginx.conf').write_text('events {}\nhttp { server { listen 13047; location /gitea/ { proxy_pass http://127.0.0.1:13048/; proxy_set_header Host $http_host; } } }\n')
run('docker','run','--name','proof-47552-gitea','-d','-p','127.0.0.1:13048:3000',
    '-e','GITEA__server__ROOT_URL=http://127.0.0.1:13047/gitea/',
    '-e','GITEA__security__INSTALL_LOCK=true','-e','GITEA__database__DB_TYPE=sqlite3',
    '-e','GITEA__database__SQLITE_JOURNAL_MODE=WAL','-e','GITEA__database__MAX_OPEN_CONNS=1',
    '-e','GITEA__service__DISABLE_REGISTRATION=true','gitea/gitea:1.24')
run('docker','run','--name','proof-47552-nginx','-d','--network','host','-v',f'{root}/nginx.conf:/etc/nginx/nginx.conf:ro','nginx:alpine')
base = 'http://127.0.0.1:13047/gitea/api/v1'
for attempt in range(120):
    try:
        urllib.request.urlopen(base+'/version'); break
    except Exception:
        time.sleep(1)
else: raise RuntimeError('Gitea did not start')
password=secrets.token_urlsafe(24)
run('docker','exec','--user','git','proof-47552-gitea','gitea','admin','user','create',
    '--username','factory','--password',password,'--email','factory@example.invalid','--admin','--must-change-password=false')
auth='Basic '+base64.b64encode(f'factory:{password}'.encode()).decode()
def post(path,data):
    request=urllib.request.Request(base+path,data=json.dumps(data).encode(),headers={'Authorization':auth,'Content-Type':'application/json'})
    return json.load(urllib.request.urlopen(request))
token=post('/users/factory/tokens',{'name':'proof','scopes':['all']})['sha1']
post('/orgs',{'username':'ACME','visibility':'public'})
post('/orgs/ACME/repos',{'name':'REPO','auto_init':True,'default_branch':'main'})
post('/repos/ACME/REPO/branches',{'new_branch_name':'hello','old_branch_name':'main'})
post('/repos/ACME/REPO/contents/hello.txt',{'branch':'hello','content':base64.b64encode(b'hello\n').decode(),'message':'Add hello'})
pr=post('/repos/ACME/REPO/pulls',{'head':'hello','base':'main','title':'Add hello','body':'A synthetic pull request for the subpath URL reproduction.'})
import os
run(str(root/'gt'),'auth','login','--host','http://127.0.0.1:13047/gitea','--with-token','--credential-store','file',input=token.encode(),env={**os.environ,'GITEA_CLI_CONFIG_DIR':str(root/'gt-config')})
print(pr['html_url'])
