"""Synthetic Forgejo fixture used for PR 45291 evidence.
Requires a fresh Forgejo 11 at loopback port 3917 with INSTALL_LOCK=true,
a tester administrator, and gt 2.0. Configure the tester credentials through
FORGEJO_TEST_PASSWORD. Set PROOF_ROOT to an empty scratch folder.
The scenario uses the printed commit SHA in both link variants.
"""
import base64
import json
import os
from pathlib import Path
import subprocess
import urllib.request

root = Path(os.environ['PROOF_ROOT'])
repo = root / 'seed'
repo.mkdir()
password = os.environ['FORGEJO_TEST_PASSWORD']
auth = 'Basic ' + base64.b64encode(('tester:' + password).encode()).decode()
origin = 'http://127.0.0.1:3917'

def api(path, data):
    request = urllib.request.Request(origin + '/api/v1/' + path,
        data=json.dumps(data).encode(),
        headers={'Authorization': auth, 'Content-Type': 'application/json'})
    with urllib.request.urlopen(request) as response:
        return json.load(response)

def git(*args):
    return subprocess.check_output(['git', *args], cwd=repo, text=True).strip()

api('user/repos', {'name': 'sha256demo', 'object_format_name': 'sha256', 'default_branch': 'main'})
git('init', '--object-format=sha256', '--initial-branch=main')
git('config', 'user.name', 'Scenario')
git('config', 'user.email', 'scenario@example.invalid')
(repo / 'notes.txt').write_text('one\ntwo\nthree\nfour\n')
git('add', '.')
git('commit', '-m', 'Initial notes')
git('checkout', '-b', 'feature')
(repo / 'notes.txt').write_text('one\ntwo\nthree\nfour\nfive\n')
git('commit', '-am', 'Add line five')
commit = git('rev-parse', 'HEAD')
(repo / 'other.txt').write_text('Another change\n')
git('add', '.')
git('commit', '-m', 'Add other file')
git('remote', 'add', 'origin', origin + '/tester/sha256demo.git')
git('-c', 'http.extraHeader=Authorization: ' + auth, 'push', 'origin', 'main', 'feature')
api('repos/tester/sha256demo/pulls', {'title': 'Add line five', 'base': 'main', 'head': 'feature'})
print('Commit used in both links:', commit)
print('Authenticate gt to this server, then inherit GITEA_CLI_CONFIG_DIR into the scenario runner.')
