"""Create an isolated, real Forgejo fixture. Requires docker, tea and a hosts entry.
Set FIXTURE_DIR to a private temporary directory. Never upload its generated config.
Add 127.0.0.1 git.example.test to hosts for the duration of the run.
Run the scenario with XDG_CONFIG_HOME=<FIXTURE_DIR>/config inherited by the app.
Expose tea on the scenario runner's existing executable search path.
"""
import os, pathlib, subprocess, secrets, json, urllib.request, base64, time
root = pathlib.Path(os.environ['FIXTURE_DIR'])
root.mkdir(parents=True, exist_ok=True)
container = 'proof-40271-forgejo'
subprocess.run(['docker','run','-d','--name',container,'-p','127.0.0.1:18871:3000',
 '-e','FORGEJO__security__INSTALL_LOCK=true','-e','FORGEJO__database__DB_TYPE=sqlite3',
 '-e','FORGEJO__server__ROOT_URL=http://git.example.test:18871/',
 '-e','FORGEJO__server__DOMAIN=git.example.test',
 '-e','FORGEJO__service__DISABLE_REGISTRATION=true','codeberg.org/forgejo/forgejo:13'],check=True)
password = secrets.token_urlsafe(24)
for attempt in range(60):
 try:
  urllib.request.urlopen('http://127.0.0.1:18871/api/v1/version'); break
 except OSError: time.sleep(1)
subprocess.run(['docker','exec','--user','git',container,'forgejo','admin','user','create',
 '--username','scenario','--password',password,'--email','scenario@example.test','--admin',
 '--must-change-password=false'],check=True)
auth = 'Basic '+base64.b64encode(('scenario:'+password).encode()).decode()
def post(path, data):
 req=urllib.request.Request('http://127.0.0.1:18871/api/v1'+path,
  data=json.dumps(data).encode(),headers={'Authorization':auth,'Content-Type':'application/json'})
 return json.load(urllib.request.urlopen(req))
token=post('/users/scenario/tokens',{'name':'proof','scopes':['all']})['sha1']
post('/user/repos',{'name':'demo','auto_init':True})
post('/repos/scenario/demo/issues',{'title':'Self-hosted issue opens inside the thread',
 'body':'Synthetic Forgejo issue for link resolution proof.'})
env={**os.environ,'XDG_CONFIG_HOME':str(root/'config'),'GITEA_SERVER_TOKEN':token}
subprocess.run(['tea','login','add','--name','proof','--url','http://git.example.test:18871'],env=env,check=True)
print('Created synthetic repository scenario/demo and issue 1. Stop and remove the container after proof.')
