"""Build the self-hosted Git download from an explicit allowlist. Requires Git and Python 3.8+."""
import argparse
import io
import os
from pathlib import Path
import re
import shutil
import subprocess
import tarfile
import tempfile

ROOT = Path(__file__).resolve().parent
ROOT_FILES = ('README.md', 'LICENSE', 'DATA-LICENSE.txt', 'build_data.py', 'package_source.py')
APP_FILES = ('index.html', 'style.css', 'app.js', 'data.json', 'stadium.jpg', 'social.jpg', 'source.html')
TRACKED = ROOT_FILES + tuple('dist/' + name for name in APP_FILES)
BROWSABLE = {
    'README.md': 'README.md', 'LICENSE.txt': 'LICENSE', 'DATA-LICENSE.txt': 'DATA-LICENSE.txt',
    'build_data.py': 'build_data.py', 'package_source.py': 'package_source.py',
    'index.html.txt': 'dist/index.html',
}
BUDGET = 4_000_000  # Compressed deployment size, in decimal bytes.
DATE = '2026-12-02T00:00:00+00:00'


def git(path, *args):
    env = {k: os.environ[k] for k in ('PATH', 'SystemRoot', 'TMPDIR', 'TEMP', 'TMP') if k in os.environ}
    env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT='0',
               LC_ALL='C', TZ='UTC', GIT_AUTHOR_DATE=DATE, GIT_COMMITTER_DATE=DATE,
               GIT_AUTHOR_NAME='Fieldnote Research', GIT_COMMITTER_NAME='Fieldnote Research',
               GIT_AUTHOR_EMAIL='source@fieldnote.invalid', GIT_COMMITTER_EMAIL='source@fieldnote.invalid')
    return subprocess.run(['git', '-c', 'pack.threads=1', *args], cwd=path, env=env,
                          check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout


def checked_input(name):
    path = ROOT / name
    if not path.is_file() or path.resolve() != path or path.stat().st_size == 0:
        raise ValueError('Missing, linked, or empty allowlisted input: ' + name)
    return path


def copy(source, dest):
    dest.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(source, dest)


def compressed_size(stage):
    buffer = io.BytesIO()
    with tarfile.open(fileobj=buffer, mode='w:gz', compresslevel=6) as archive:
        for path in sorted(stage.rglob('*')):
            if path.is_file():
                archive.add(path, arcname=path.relative_to(stage), recursive=False)
    return len(buffer.getvalue())


def package():
    paths = {name: checked_input(name) for name in TRACKED}
    # Use a new repository, not the containing project, global Git identity, or an existing .git.
    with tempfile.TemporaryDirectory(prefix='false-hope-package-', dir=ROOT) as temp:
        temp = Path(temp)
        checkout, stage = temp/'checkout', temp/'deploy'
        checkout.mkdir()
        stage.mkdir()
        for name, path in paths.items():
            copy(path, checkout/name)
        git(checkout, 'init', '--object-format=sha1', '--initial-branch=main', '--template=')
        git(checkout, 'add', '--', *TRACKED)
        git(checkout, 'commit', '--no-gpg-sign', '-m', 'Publish False Hope source and season data')
        stored = git(checkout, 'ls-tree', '-r', '--name-only', 'HEAD').decode().splitlines()
        if set(stored) != set(TRACKED):
            raise ValueError('Git snapshot differs from the allowlist')
        git(checkout, 'repack', '-adf')
        git(checkout, 'update-server-info')
        # Keeping these files alone supports Git's static HTTP transport without exposing .git/config.
        dotgit = checkout/'.git'
        repo = stage/'repository'
        for name in ('HEAD', 'info/refs', 'objects/info/packs'):
            copy(dotgit/name, repo/name)
        pack_list = (repo/'objects/info/packs').read_text().splitlines()
        packs = [line[2:] for line in pack_list if line.startswith('P ')]
        if len(packs) != 1 or not re.fullmatch(r'pack-[0-9a-f]{40}\.pack', packs[0]):
            raise ValueError('Expected a single Git SHA-1 pack')
        for name in (packs[0], packs[0][:-5]+'.idx'):
            copy(dotgit/'objects/pack'/name, repo/'objects/pack'/name)
        git(checkout, 'bundle', 'create', str(stage/'source.bundle'), '--all')
        for name, original in BROWSABLE.items():
            copy(paths[original], stage/'source'/name)
        for name in APP_FILES:
            copy(paths['dist/'+name], stage/name)
        size = compressed_size(stage)
        if size >= BUDGET:
            raise ValueError(f'Deployable archive would be {size:,} bytes (cap {BUDGET:,}); no files replaced')
        # Promote only owned generated paths; never edit any hand-authored page or asset.
        for name in ('source', 'repository', 'source.bundle'):
            target = ROOT/'dist'/name
            saved = temp/('previous-'+name)
            if target.is_symlink():
                raise ValueError('Refusing to replace symlink: ' + name)
            if target.exists():
                target.rename(saved)
            try:
                (stage/name).rename(target)
            except OSError:
                if saved.exists():
                    saved.rename(target)
                raise
        commit = git(checkout, 'rev-parse', 'HEAD').decode().strip()
        print(f'{commit} | {len(stored)} tracked files | {size:,} compressed deployment bytes')


if __name__ == '__main__':
    argparse.ArgumentParser(description=__doc__).parse_args()
    package()
