"""Real Forgejo fixture. Set FORGEJO_PROOF_DIR to an empty scratch directory.
Requires Docker, ssh-keygen, Python 3; ports 13885 and 12285 must be free.
Downloaded binaries stay in the scratch directory; expose fj/gt on the existing PATH.
Run the scenario with GITEA_CLI_CONFIG_DIR=$FORGEJO_PROOF_DIR/auth/gt and
XDG_DATA_HOME=$FORGEJO_PROOF_DIR/auth/fj inherited by the app.
"""
import os, pathlib, subprocess, urllib.request, json, tarfile, sys
p = pathlib.Path(os.environ['FORGEJO_PROOF_DIR'])
p.mkdir(parents=True, exist_ok=True)
def sh(*args): return subprocess.check_output(args, text=True).strip()
def download(url, name): urllib.request.urlretrieve(url, p / name)
if "--seed" not in sys.argv:
    download('https://gitea.com/gitea/cli/releases/download/v2.0.0/gitea-cli-2.0.0-linux-amd64', 'gt')
    download('https://codeberg.org/forgejo-contrib/forgejo-cli/releases/download/v0.7.0/forgejo-cli-x86_64-linux.tar.gz', 'fj.tar.gz')
    with tarfile.open(p / 'fj.tar.gz') as archive: archive.extractall(p, filter='data')
    for name in ('gt', 'fj'): (p/name).chmod(0o755)
    sh('docker','run','--name','proof-45885-forgejo','-d','-p','13885:3000','-p','12285:22','-e','FORGEJO__security__INSTALL_LOCK=true','-e','FORGEJO__database__DB_TYPE=sqlite3','-e','FORGEJO__server__ROOT_URL=http://localhost:13885/','-e','FORGEJO__server__SSH_DOMAIN=localhost','-e','FORGEJO__server__SSH_PORT=12285','codeberg.org/forgejo/forgejo@sha256:d05b9e587f02a746784d42c815c486b1d4f138646128f990a841833f513fe088')
    print('Wait for http://localhost:13885/api/v1/version, then run this script with --seed.')
    sys.exit(0)
# Run only after the real Forgejo HTTP endpoint is ready.
sh('docker','exec','-u','git','proof-45885-forgejo','forgejo','admin','user','create','--username','proof','--password','Proof45885Password','--email','proof@example.invalid','--admin','--must-change-password=false')
token = sh('docker','exec','-u','git','proof-45885-forgejo','forgejo','admin','user','generate-access-token','--username','proof','--token-name','proof','--scopes','all','--raw')
(p/'token').write_text(token)
def post(path,data):
    request = urllib.request.Request('http://localhost:13885/api/v1/'+path, data=json.dumps(data).encode(), headers={'Authorization':'token '+token,'Content-Type':'application/json'})
    return json.load(urllib.request.urlopen(request))
post('orgs', {'username':'acme','full_name':'Acme'})
post('orgs/acme/repos', {'name':'project','auto_init':True,'default_branch':'main'})
post('repos/acme/project/issues', {'title':'Existing issue for factory-pr-45885','body':'Synthetic proof data for SSH web origin resolution.'})
sh('ssh-keygen','-t','ed25519','-N','','-f',str(p/'id_ed25519'),'-C','proof@example.invalid')
post('user/keys', {'title':'proof','key':(p/'id_ed25519.pub').read_text()})
for path in ('auth/gt','auth/fj'):
    (p/path).mkdir(parents=True,exist_ok=True)
print('Fixture ready. Run forgejo-ssh-http-origin.e2e.ts with FORGEJO_PROOF_DIR inherited.')
