#!/usr/bin/env python3
"""Run representative Library Reference clients in disposable, isolated projects.

This checks clients against trusted predefined contracts, not library-body proofs.
Fixed output fixtures are compared exactly. Other corpora compare native output to
JIT output, which establishes backend agreement rather than an independent oracle.
"""
from __future__ import annotations
import argparse
from datetime import datetime
import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
from zoneinfo import ZoneInfo
from inventory import MANUALS, ROOT, compiler_path, sha

REPORT = MANUALS / 'authoring/library-validation.json'


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--compiler')
    args = parser.parse_args()
    compiler = compiler_path(args.compiler)
    cases = []
    report = {
        'schema_version': 1,
        'source_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
        'compiler_sha256': sha(compiler), 'platform': platform.platform(), 'completed': False,
        'scope': 'Representative public-library clients: frontend/flow, client proof, JIT and native. Predefined bodies/contracts, model encodings, C runtime and libm remain trusted. No fresh library-body GNATprove sweep or other-host guarantee.',
        'not_executed': ['Fresh installation', 'All library bodies proved independently', 'Every declaration block exercised at runtime', 'External Ada or Python implementation comparison', 'Cross-platform execution'],
        'cases': cases, 'inputs': {},
        'recorded_at': datetime.now(ZoneInfo('America/Vancouver')).isoformat(timespec='seconds'),
    }
    def save(): REPORT.write_text(json.dumps(report, indent=2) + '\n')
    save()
    with tempfile.TemporaryDirectory(prefix='verada-library-manual-') as temporary:
        scratch = Path(temporary)
        env = os.environ.copy()
        env.update(XDG_CACHE_HOME=str(scratch / 'cache'), XDG_STATE_HOME=str(scratch / 'state'),
                   XDG_CONFIG_HOME=str(scratch / 'config'), GHCRTS='-N2', NO_COLOR='1')
        env.pop('VERADA_RT_DEBUG', None)
        env.pop('VERADA_SOLVER_TIMEOUT', None)
        def normal(value): return value.replace(str(scratch), '<scratch>').replace(str(ROOT), '<repository>')
        def copy(relative):
            target = scratch / relative
            shutil.copytree(ROOT / relative, target,
                            ignore=shutil.ignore_patterns('.verada', '.git', '__pycache__', 'gnat'))
            for file in target.rglob('*'):
                if file.is_file():
                    report['inputs'][str(Path(relative) / file.relative_to(target))] = sha(file)
            save()
            return target
        def run(label, argv, *, expected_stdout=None, oracle, source, adaptation=None):
            record = {'case': label, 'source': str(source), 'oracle': oracle,
                      'command': [normal(str(x)) for x in argv], 'expected_exit': 0, 'outcome': 'running'}
            if adaptation: record['adaptation'] = adaptation
            if expected_stdout is not None: record['expected_stdout'] = expected_stdout
            cases.append(record); save()
            try:
                result = subprocess.run(list(map(str, argv)), cwd=scratch, env=env,
                                        text=True, capture_output=True, timeout=180)
                record.update(exit=result.returncode, stdout=normal(result.stdout), stderr=normal(result.stderr))
                if result.returncode != 0: raise AssertionError('Expected success')
                if expected_stdout is not None and result.stdout != expected_stdout:
                    raise AssertionError('Exact stdout differs from ' + oracle)
                record['outcome'] = 'passed'; save()
                return result.stdout
            except Exception as exc:
                record.update(outcome='failed', error=str(exc)); save(); raise
        def project(label, relative):
            path = copy(relative); config = path / 'verada.toml'
            golden = path / 'expected.stdout'
            expected = golden.read_text() if golden.exists() else None
            common = {'source': relative, 'oracle': 'successful frontend/flow or client-proof exit'}
            run(label + '.check', [compiler, 'check', '--project', config], **common)
            run(label + '.prove', [compiler, 'prove', '--no-cache', '--project', config], **common)
            output = run(label + '.jit', [compiler, 'run', '--no-cache', '--project', config],
                         expected_stdout=expected, source=relative,
                         oracle='source expected.stdout exact comparison' if expected is not None else 'successful JIT exit; native comparison follows')
            executable = scratch / (label + '-native')
            run(label + '.build', [compiler, 'build', '--no-cache', '--project', config, '-o', executable], **common)
            run(label + '.native', [executable], expected_stdout=expected if expected is not None else output,
                source=relative, oracle='source expected.stdout exact comparison' if expected is not None else 'exact agreement with JIT output; not an independent functional oracle')
        for family in ['strings', 'numerics', 'collections', 'io-process', 'fixed-io', 'scanning', 'text-io-instances', 'characters', 'unbounded', 'environment', 'end-error', 'wide-text-io', 'directories', 'ada-bounded-containers', 'wide-maps-hash', 'wide-wide-characters']:
            project('manual.' + family, 'docs/manuals/examples/library/' + family)
        declarations = copy('docs/manuals/examples/library/generic-instances')
        for syntax in ['adb', 'varc']:
            for command in ['check', 'prove']:
                run('generic-declarations.' + syntax + '.' + command,
                    [compiler, command, '--no-cache', declarations / ('instances.' + syntax)],
                    source='docs/manuals/examples/library/generic-instances/instances.' + syntax,
                    oracle='all supplied imports and generic/nested-generic declarations accepted; not all operations exercised')
        for family in ['containers', 'varc-containers', 'vibe-collections', 'graphs', 'l4b', 'interfacing']:
            project('corpus.' + family, 'test/corpus-' + family)
        for family, filename in [('texts', 'main.vadb'), ('varc-texts', 'main.va'),
                                 ('unbounded-sets-maps', 'main.vadb'), ('doubly-linked-lists', 'main.vadb'),
                                 ('arena-model', 'main.vadb'), ('big-integers', 'main.vadb'), ('text-files', 'main.vadb')]:
            relative = 'test/programs/run/' + family
            path = copy(relative); source = path / filename
            adaptation = None
            if family == 'text-files':
                # The golden test uses a fixed /tmp file. Keep this replay's writes disposable.
                source.write_text(source.read_text().replace('/tmp/verada-text-files-test.txt', str(scratch / 'text-files-test.txt')))
                adaptation = 'Only the literal file path is redirected from a shared /tmp name into this disposable scratch directory.'
            run('program.' + family + '.jit', [compiler, 'run', '--no-cache', source],
                source=relative, expected_stdout=(path / 'expected.stdout').read_text(),
                oracle='source expected.stdout exact comparison', adaptation=adaptation)
        for family in ['functional-sets-maps', 'big-reals', 'formal-maps', 'ordered-sets',
                       'unbounded-maps', 'unbounded-ordered-sets', 'texts']:
            relative = 'test/programs/prove/' + family
            path = copy(relative)
            run('proof-client.' + family, [compiler, 'prove', '--no-cache', path / 'main.vadb'],
                source=relative, oracle='successful client proof; embedded predefined implementation remains trusted')
        run('declaration-freshness', ['python3', MANUALS / 'authoring/library-generation.py', '--compiler', compiler],
            source='lib/*.vads and docs/manuals/reference/library/*.md',
            oracle='regenerated exact compiler output or labeled source-derived fallback matches every saved reference and provenance entry')
    report['completed'] = True
    report['successful_checks'] = sum(case['outcome'] == 'passed' for case in cases)
    save()
    print(f'Library validation completed: {len(cases)} checks; {REPORT.relative_to(ROOT)}')


if __name__ == '__main__': main()
