"""Freeze, build and check the separate local 0.46.8 player once.

Usage: python Tools/Run-Production0468.py freeze|build|startup
Exclusive outputs; no publication, campaign replay or previous-player changes.
"""
from pathlib import Path
from datetime import datetime, timezone
import argparse
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import time
import uuid

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'Docs/Angel-Land-Story/qa/0.46.8'
PLAYER = ROOT / 'Builds/Production0468Windows'
UNITY = Path('C:/Program Files/Unity/Hub/Editor/6000.3.24f1/Editor/Unity.exe')
VERSION = '0.46.8'
PAYLOAD = ('AngelLandStory.exe', 'AngelLandStory_Data/Managed/Assembly-CSharp.dll',
           'AngelLandStory_Data/resources.assets', 'AngelLandStory_Data/resources.assets.resS',
           'AngelLandStory_Data/globalgamemanagers')
BUILD_LOG = OUT / 'unity-build.log'
MANIFEST = OUT / 'source-build.json'


def require(value, message):
    if not value:
        raise RuntimeError(message)


def now(): return datetime.now(timezone.utc).isoformat()
def read(path): return json.loads(path.read_text(encoding='utf-8-sig'))


def sha(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def write_new(path, data):
    with path.open('x', encoding='utf-8', newline='\n') as stream:
        stream.write(json.dumps(data, indent=2, ensure_ascii=False) + '\n')


def source_files():
    paths = [p for directory in ('Assets/Scripts', 'Assets/Editor')
             for p in (ROOT / directory).rglob('*.cs')]
    for directory, pattern in [('Assets/Resources/Levels', '*.json'),
                               ('Assets/Resources/Voice', '*.json'),
                               ('Assets/Resources/Voice/Clips', '*.wav'),
                               ('Assets/Resources/Materials', '*.shader'),
                               ('Assets/Resources/GameArt', '*.png'),
                               ('Assets/Resources/GameArt', '*.png.meta'),
                               ('Assets/Resources/Voice/Clips', '*.wav.meta'),
                               ('Assets/Resources/GameAudio', '*.wav'),
                               ('Assets/Resources/GameAudio', '*.wav.meta')]:
        paths.extend((ROOT / directory).glob(pattern))
    paths.extend(ROOT / name for name in ('Assets/Scenes/Sonnenhain.unity',
                 'Assets/Resources/GameConfig.asset', 'Assets/Branding/AngelLandStoryIcon.png',
                 'ProjectSettings/ProjectVersion.txt'))
    return {p.relative_to(ROOT).as_posix(): sha(p) for p in sorted(set(paths))}


def payload(): return {name: sha(PLAYER / name) for name in PAYLOAD}


def hidden_process(args):
    startup = subprocess.STARTUPINFO()
    startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startup.wShowWindow = 0
    return subprocess.Popen([str(a) for a in args], cwd=ROOT, startupinfo=startup,
                            creationflags=subprocess.CREATE_NO_WINDOW)


def wait_owned(process, seconds):
    try:
        return process.wait(timeout=seconds), False
    except subprocess.TimeoutExpired:
        process.terminate()
        return process.wait(timeout=15), True


def historical(path, recorded):
    info = read(recorded)
    recorded_hashes = (info['payloadSha256'] if 'payloadSha256' in info else
                       {name: item['sha256'] for name, item in info['player'].items()})
    current = {name: sha(path / name) for name in recorded_hashes}
    require(current == recorded_hashes, 'Historical player no longer matches its recorded identity: ' + str(path))
    return {'player': str(path / 'AngelLandStory.exe'), 'evidence': str(recorded),
            'evidenceSha256': sha(recorded), 'recordedPayloadSha256': recorded_hashes,
            'payloadStillMatchesHistoricalEvidence': True}


def freeze():
    require(not PLAYER.exists(), 'Preserve existing release player: ' + str(PLAYER))
    OUT.mkdir(parents=True, exist_ok=True)
    require(not MANIFEST.exists(), 'Preserve existing source freeze')
    require(not (OUT / 'ProjectSettings-before.asset').exists(), 'Preserve previous settings snapshot')
    settings = ROOT / 'ProjectSettings/ProjectSettings.asset'
    with settings.open('rb') as src, (OUT / 'ProjectSettings-before.asset').open('xb') as dst:
        shutil.copyfileobj(src, dst)
    data = {'version': VERSION, 'frozenUtc': now(), 'player': str(PLAYER),
            'sourceFiles': source_files(), 'settingsBeforeSHA256': sha(settings),
            'settingsBefore': str(OUT / 'ProjectSettings-before.asset'),
            'runnerSHA256': sha(Path(__file__)),
            'development': historical(ROOT / 'Builds/Development0468Windows',
                ROOT / 'Docs/Angel-Land-Story/qa/0.46.8-development/source-build.json'),
            'previousDevelopment': historical(ROOT / 'Builds/Development0467Windows',
                ROOT / 'Docs/Angel-Land-Story/qa/0.46.7-development/source-build.json'),
            'lioReview5': historical(ROOT / 'Builds/LioGroundDevelopment20261003-Review5',
                ROOT / 'Builds/LioGroundDevelopment20261003-Review5/GroundReview/tested-build.json'),
            'lioReview5SourceManifest': str(ROOT / 'output/lio-ground-20261003/review5-source-before-build.json'),
            'lioReview5SourceManifestSHA256': sha(ROOT / 'output/lio-ground-20261003/review5-source-before-build.json')}
    write_new(MANIFEST, data)
    write_new(OUT / 'compiled-sources.json', {'version': VERSION, 'frozenUtc': data['frozenUtc'],
        'files': {name: digest for name, digest in data['sourceFiles'].items() if name.endswith('.cs')}})
    print('Frozen local 0.46.8 sources, historical identities and ProjectSettings.', flush=True)


def build():
    data = read(MANIFEST)
    require(data['sourceFiles'] == source_files(), 'Source changed since freeze')
    require(not PLAYER.exists() and not BUILD_LOG.exists() and not (OUT / 'build-process.json').exists(),
            'Preserve previous build or evidence')
    require(sha(ROOT / 'ProjectSettings/ProjectSettings.asset') == data['settingsBeforeSHA256'],
            'Project settings changed before build')
    started = now()
    process = hidden_process([UNITY, '-batchmode', '-quit', '-projectPath', ROOT,
                              '-executeMethod', 'BuildSonnenhain.BuildProduction0468', '-logFile', BUILD_LOG])
    print('Owned release Unity PID ' + str(process.pid), flush=True)
    code, timeout = wait_owned(process, 1800)
    sources_unchanged = data['sourceFiles'] == source_files()
    settings = ROOT / 'ProjectSettings/ProjectSettings.asset'
    before = (OUT / 'ProjectSettings-before.asset').read_text(encoding='utf-8-sig')
    after = settings.read_text(encoding='utf-8-sig')
    normalize = lambda text: re.sub(r'(?m)^(\s*bundleVersion:)\s*[^\r\n]+', r'\1 <VERSION>', text)
    settings_only_version = normalize(before) == normalize(after) and bool(re.search(r'(?m)^\s*bundleVersion: 0\.46\.8\s*$', after))
    log = BUILD_LOG.read_text(encoding='utf-8', errors='replace') if BUILD_LOG.exists() else ''
    succeeded = code == 0 and not timeout and 'AURALIS_BUILD Succeeded' in log
    proof = {'version': VERSION, 'startedUtc': started, 'completedUtc': now(), 'pid': process.pid,
             'exitCode': code, 'timedOut': timeout, 'buildSucceeded': succeeded,
             'developmentBuild': False, 'method': 'BuildSonnenhain.BuildProduction0468',
             'log': str(BUILD_LOG), 'logSha256': sha(BUILD_LOG) if BUILD_LOG.exists() else None,
             'sourceManifestSha256': sha(MANIFEST), 'sourcesUnchanged': sources_unchanged,
             'settingsOnlyBundleVersionChanged': settings_only_version, 'settingsAfterSHA256': sha(settings)}
    if succeeded:
        proof['payloadSha256'] = payload()
        proof['embeddedVersionPresent'] = VERSION.encode() in (PLAYER / PAYLOAD[-1]).read_bytes()
        proof['fontLicensesMatch'] = all(sha(p) == sha(PLAYER / 'Licenses' / p.name)
                                      for p in (ROOT / 'ThirdParty/Fonts').iterdir() if p.is_file())
    write_new(OUT / 'build-process.json', proof)
    require(succeeded and sources_unchanged and settings_only_version and proof['embeddedVersionPresent']
            and proof['fontLicensesMatch'], 'Build verification failed; preserve build/process evidence')
    print(json.dumps(proof, indent=2), flush=True)


def isolated_save(path):
    p = Path(path)
    require(p.is_absolute(), 'QA save path must be absolute')
    parts = p.parts
    require(len(parts) >= 3 and parts[-3] == 'AuralisProfileQA'
            and re.fullmatch(r'[0-9a-fA-F]{32}', parts[-2]) is not None
            and re.fullmatch(r'auralis-profile-[1-4]\.json', parts[-1]) is not None,
            'Refusing save outside the isolated AuralisProfileQA slot layout')
    uuid.UUID(hex=parts[-2])
    for item in [p, *p.parents]:
        require(not (getattr(item.lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT),
                'Refusing linked QA save path')
    require(p.is_file(), 'Missing declared isolated save')
    return p


def startup():
    frozen, built = read(MANIFEST), read(OUT / 'build-process.json')
    require(built['buildSucceeded'] and built['sourcesUnchanged'] and frozen['sourceFiles'] == source_files(),
            'Exact frozen successful build required')
    before = payload()
    require(before == built['payloadSha256'], 'Player differs from built payload')
    capture, archive = ROOT / 'Builds/Release0468SmokeQA', OUT / 'ReleaseStartup'
    require(not capture.exists() and not archive.exists(), 'Preserve earlier startup evidence')
    archive.mkdir()
    log = archive / 'player.log'
    started = now()
    process = hidden_process([PLAYER / 'AngelLandStory.exe', '--auralis-qa', '--auralis-offscreen',
                              '--auralis-release-0468-smoke', '-screen-width', '1920', '-screen-height',
                              '1080', '-screen-fullscreen', '0', '-logFile', log])
    print('Owned 0.46.8 startup PID ' + str(process.pid), flush=True)
    code, timeout = wait_owned(process, 360)
    failures = []
    if capture.exists():
        for item in capture.iterdir():
            require(item.is_file() and not item.is_symlink(), 'Unexpected nested/linked startup output')
            with item.open('rb') as src, (archive / item.name).open('xb') as dst:
                shutil.copyfileobj(src, dst)
    full_log = log.read_text(encoding='utf-8', errors='replace') if log.exists() else ''
    findings = [line for line in full_log.splitlines() if re.search(
        r'\b[\w.]*Exception\b|Assertion fail|Shader error|Crash!!!|Fatal error|887a0007|Failed to create graphics device|^Cannot set the parent of the GameObject .* while its new parent .* is being destroyed', line, re.I)]
    proof = {'version': VERSION, 'startedUtc': started, 'completedUtc': now(), 'pid': process.pid,
             'player': str(PLAYER / 'AngelLandStory.exe'), 'exitCode': code, 'timedOut': timeout,
             'flag': '--auralis-release-0468-smoke', 'payloadSha256': before, 'payloadSha256After': payload(),
             'sourceManifestSha256': sha(MANIFEST), 'sourcesUnchanged': frozen['sourceFiles'] == source_files(),
             'assemblySha256': before[PAYLOAD[1]], 'logFindings': findings,
             'nativeLogSha256': sha(log) if log.exists() else None,
             'scope': 'Exact local 0.46.8 startup, title version, empty isolated QA profile, normal virtual Gamepad start/walk/pause/save/disk reload/continue. Separate route/survey checks have their own reports; no inherited user save or human acceptance.'}
    try:
        report, evidence = read(archive / 'report.json'), read(archive / 'release-0468-evidence.json')
        fresh = datetime.fromisoformat(report['utc'].replace('Z', '+00:00')) >= datetime.fromisoformat(started)
        proof.update({'runtimeErrors': report['runtimeErrors'], 'checks': len(report['checks']),
                      'failedChecks': sum(not c['passed'] for c in report['checks']), 'freshReport': fresh,
                      'reportSha256': sha(archive / 'report.json'),
                      'evidenceSha256': sha(archive / 'release-0468-evidence.json'),
                      'titleVersion': evidence['titleVersion'],
                      'actualStartupBoundary': all(evidence.get(k) is True for k in ['qaModeChoiceRequired', 'started', 'diskRead', 'continuedFromDisk', 'finalSavedTitle'])})
        require(fresh and report['runtimeErrors'] == 0 and len(report['checks']) == 33
                and all(c['passed'] for c in report['checks'])
                and report['checks'][-1]['name'] == 'No release startup runtime errors', 'Incomplete or failed startup checks')
        require(evidence['version'] == VERSION and evidence['titleVersion'] == 'SONNENHAIN  ·  0.46.8'
                and proof['actualStartupBoundary'], 'Wrong version/title or incomplete save/continue boundary')
        save = isolated_save(evidence['savePath'])
        target = archive / 'final-qa-profile.json'
        with save.open('rb') as src, target.open('xb') as dst:
            shutil.copyfileobj(src, dst)
        proof['isolatedSave'] = {'path': str(target), 'sha256': sha(target), 'sourceSha256': sha(save),
                                 'evidenceSha256': evidence['savedSha256'], 'isolatedPathVerified': True}
        require(proof['isolatedSave']['sha256'] == sha(save) == evidence['savedSha256'].lower(),
                'Copied isolated save differs from actual runtime evidence')
    except Exception as error:
        failures.append(str(error))
    if code != 0 or timeout: failures.append('Owned startup process did not exit cleanly')
    if not full_log or findings: failures.append('Missing or faulty full native player/shutdown log')
    if proof['payloadSha256After'] != before: failures.append('Player payload changed during check')
    if not proof['sourcesUnchanged']: failures.append('Frozen sources changed during check')
    proof['nativeShutdownClean'] = code == 0 and not timeout and bool(full_log) and not findings
    proof['failures'], proof['passed'] = failures, not failures
    write_new(archive / 'player-process.json', proof)
    print(json.dumps({k: proof.get(k) for k in ['passed', 'checks', 'failedChecks', 'runtimeErrors', 'exitCode', 'titleVersion', 'nativeShutdownClean', 'failures']}, indent=2), flush=True)
    require(not failures, 'Startup verification failed; all evidence preserved')


def focused(flag, name):
    require(flag.startswith('--auralis-') and re.fullmatch(r'[A-Za-z0-9]+QA', name), 'Explicit bounded route required')
    route_source = (ROOT / 'Assets/Scripts/Core/ProductionQaRoutes.cs').read_text(encoding='utf-8')
    flags = re.findall(r'"([^"]+)"', route_source.split('Flags={', 1)[1].split('};', 1)[0])
    names = re.findall(r'"([^"]+)"', route_source.split('Folders={', 1)[1].split('};', 1)[0])
    require(flag in flags and names[flags.index(flag)] == name, 'Flag/capture pair does not match compiled routing')
    frozen, built = read(MANIFEST), read(OUT / 'build-process.json')
    require(built['buildSucceeded'] and frozen['sourceFiles'] == source_files(), 'Exact frozen release required')
    before = payload()
    require(before == built['payloadSha256'], 'Player differs from built payload')
    capture, archive = ROOT / 'Builds' / name, OUT / name
    require(not capture.exists() and not archive.exists(), 'Preserve previous focused evidence before rerunning')
    archive.mkdir()
    log = archive / 'player.log'
    started = now()
    process = hidden_process([PLAYER / 'AngelLandStory.exe', '--auralis-qa', '--auralis-offscreen', flag,
                              '-screen-width', '1920', '-screen-height', '1080', '-screen-fullscreen', '0', '-logFile', log])
    print('Owned release QA PID ' + str(process.pid) + ': ' + name, flush=True)
    code, timeout = wait_owned(process, 480)
    if capture.exists():
        for item in capture.iterdir():
            require(item.is_file() and not item.is_symlink(), 'Unexpected nested/linked QA output')
            with item.open('rb') as src, (archive / item.name).open('xb') as dst:
                shutil.copyfileobj(src, dst)
    full_log = log.read_text(encoding='utf-8', errors='replace') if log.exists() else ''
    findings = [line for line in full_log.splitlines() if re.search(
        r'\b[\w.]*Exception\b|Assertion fail|Shader error|Crash!!!|Fatal error|887a0007|Failed to create graphics device', line, re.I)]
    report = read(archive / 'report.json') if (archive / 'report.json').exists() else {}
    checks = report.get('checks', [])
    proof = {'version': VERSION, 'flag': flag, 'startedUtc': started, 'completedUtc': now(), 'pid': process.pid,
             'exitCode': code, 'timedOut': timeout, 'assemblySha256': before[PAYLOAD[1]],
             'payloadSha256': before, 'sourcesUnchanged': frozen['sourceFiles'] == source_files(),
             'payloadUnchanged': before == payload(), 'logFindings': findings,
             'checks': len(checks), 'failedChecks': sum(not c['passed'] for c in checks),
             'runtimeErrors': report.get('runtimeErrors'), 'nativeShutdownClean': code == 0 and not timeout and bool(full_log) and not findings}
    proof['passed'] = bool(checks) and proof['failedChecks'] == 0 and proof['runtimeErrors'] == 0 and proof['nativeShutdownClean'] and proof['sourcesUnchanged'] and proof['payloadUnchanged']
    write_new(archive / 'player-process.json', proof)
    print(json.dumps({k: proof[k] for k in ['passed', 'checks', 'failedChecks', 'runtimeErrors', 'exitCode', 'logFindings']}, indent=2), flush=True)
    require(proof['passed'], 'Focused release check failed; evidence retained')


def validate(required):
    require(required and len(required) == len(set(required)), 'List each required focused release suite once')
    frozen, built = read(MANIFEST), read(OUT / 'build-process.json')
    require(built['buildSucceeded'] and built['sourcesUnchanged'] and built['developmentBuild'] is False,
            'Successful production build required')
    require(frozen['sourceFiles'] == source_files() and payload() == built['payloadSha256'], 'Release freeze changed')
    runs = []
    for name in ['ReleaseStartup', *required]:
        require(re.fullmatch(r'[A-Za-z0-9]+', name), 'Invalid suite directory')
        folder = OUT / name
        report, process = read(folder / 'report.json'), read(folder / 'player-process.json')
        require(process['passed'] and process['version'] == VERSION and process['assemblySha256'] == built['payloadSha256'][PAYLOAD[1]], 'Failed or foreign release suite: ' + name)
        require(report['checks'] and all(c['passed'] for c in report['checks']) and report['runtimeErrors'] == 0, 'Incomplete suite: ' + name)
        runs.append({'name': name, 'checks': len(report['checks']), 'report': name + '/report.json',
                     'reportSha256': sha(folder / 'report.json'), 'process': name + '/player-process.json',
                     'processSha256': sha(folder / 'player-process.json'), 'nativeLog': name + '/player.log',
                     'nativeLogSha256': sha(folder / 'player.log'), 'playerPid': process['pid']})
    proof = {'version': VERSION, 'passed': True, 'compiledUtc': built['completedUtc'], 'validatedUtc': now(),
             'buildSucceeded': True, 'developmentBuild': False, 'runtimeErrors': 0, 'failedChecks': 0,
             'nativeShutdownClean': True, 'sourceFreezeUnchanged': True, 'payloadSha256': built['payloadSha256'],
             'runs': runs, 'checks': sum(r['checks'] for r in runs),
             'scope': 'Exact production player: startup plus explicitly listed bounded routes, audio and native survey fixtures. Not a continuous campaign, physical controller/TV or human audio/style acceptance.'}
    write_new(OUT / 'release-validation.json', proof)
    print(json.dumps({'version': VERSION, 'passed': True, 'suites': len(runs), 'checks': proof['checks']}, indent=2), flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('mode', choices=('freeze', 'build', 'startup', 'run', 'validate'))
    parser.add_argument('--flag')
    parser.add_argument('--name')
    parser.add_argument('--require', nargs='+')
    args = parser.parse_args()
    if args.mode == 'run':
        require(args.flag and args.name, 'Run requires --flag and --name')
        focused(args.flag, args.name)
    elif args.mode == 'validate':
        validate(args.require)
    else:
        {'freeze': freeze, 'build': build, 'startup': startup}[args.mode]()
