#!/usr/bin/env python3
"""Exercise sync.sh's range lints without running the build/deployment script.

Run from any directory; --root selects another static checkout for regression
checks. Quiet on success so sync.sh's wrap can report failures normally.
"""
import argparse
from pathlib import Path
import re
import subprocess
import sys
import tempfile


def exactly_one(source, pattern):
    matches = re.findall(pattern, source, re.MULTILINE)
    if len(matches) != 1:
        raise ValueError(f"Expected one production definition matching {pattern!r}; found {len(matches)}")
    return matches[0].strip()


def fixtures():
    positive, negative = [], []
    for stem in ['/doc/math/lion', '/', '/foo/bar', 'https://gwern.net/doc/math/lion', '/déjà-vu']:
        for fragment in ['#history#end', '#history#', '##history', '##', '#2026#2025', '#unicode_α#β']:
            url = stem + fragment
            positive.extend([url, f'<a href="{url}">text</a>', f"<a href='{url}'>text</a>",
                             f'("{url}", metadata)', f'[text]({url})'])
        for fragment in ['#history:end', '#history:', '#:history', '#:', '#history', '', '#a%23b', '#a%2523b']:
            negative.append(f'<a href="{stem + fragment}">text</a>')
    # Former HTML whitelist; each metadata suffix is exercised by the batch below.
    positive.append('<a href="/index#newest#statistics">legacy exception</a>')
    negative.extend([
        '## Heading', '### Another heading', 'plain ## heading text',
        'https://example.com/doc#a#b', 'https://example.com/doc##',
        '<a href="https://example.com/doc#a#b">external</a>',
        '<a href="//example.com/doc#a#b">external</a>',
        '<a href="//gwern.net/doc#a#b">protocol-relative</a>',
        '<a href="https://gwern.net.example.com/doc#a#b">external</a>',
        '<a href="https://gwern.net@example.com/doc#a#b">external</a>',
        '<a href="/doc#a">has # in link text</a>',
        '<a href="/doc#a">text</a> <a href="/doc#b">two</a>',
        '/doc#a and #b are separate fragments', '<code>#history#end</code>',
        '<a href="/doc#history%23">escaped trailing hash</a>',
        'text https://example.com/doc#a#b text',
        '<a href="/doc#history:end">current</a>',
    ])
    return positive, negative


def check(root):
    source = (root / 'build/sync.sh').read_text()
    helpers = (root / 'build/bash.sh').read_text()
    assignment = exactly_one(source, r'^\s*(LEGACY_RANGE_RE=.*)$')
    metadata_check = exactly_one(source, r'^\s*(λ\(\)\{[^\n]*\$LEGACY_RANGE_RE[^\n]*metadata/[^\n]*)$')
    html_check = exactly_one(source, r'^\s*(λ\(\)\{[^\n]*\$PAGES_ALL[^\n]*\$LEGACY_RANGE_RE[^\n]*)$')
    ge = exactly_one(helpers, r'^(ge\s+\(\)[^\n]*)$')
    wrap = exactly_one(helpers, r'^(wrap \(\) \{\n[\s\S]*?^\})$')
    positive, negative = fixtures()
    failures = []
    for expected, cases in [(True, positive), (False, negative)]:
        for case in cases:
            run = subprocess.run(
                ['bash', '-c', 'set -e\n' + assignment + '\ngrep --extended-regexp -- "$LEGACY_RANGE_RE"'],
                input=case + '\n', text=True, capture_output=True, check=False)
            if run.returncode not in (0, 1) or run.stderr or (run.returncode == 0) != expected:
                failures.append(f"pattern: warning={expected}, input={case!r}, "
                                f"exit={run.returncode}, stderr={run.stderr!r}")

    # Run both actual commands through actual wrap, testing its command
    # substitution and visibility of the unexported regex. Every fixture goes
    # through HTML and both metadata globs; valid-only batches must stay quiet.
    with tempfile.TemporaryDirectory(prefix='gwern-range-lints-') as tmp:
        here = Path(tmp)
        (here / 'metadata').mkdir()
        for warning in [False, True]:
            cases = (positive if warning else []) + negative
            content = ''.join(f'case{i:04d}\t{case}\n' for i, case in enumerate(cases))
            for target in ['metadata/test.gtx', 'metadata/test.hs', 'page.html']:
                (here / target).write_text(content)
            expected = [f'case{i:04d}' for i in range(len(positive))] if warning else []
            for name, command, copies in [('metadata', metadata_check, 2), ('html', html_check, 1)]:
                program = '\n'.join([
                    'set -e', assignment, ge, wrap,
                    'red () { printf "%s\\n" "$*"; }',
                    'PAGES_ALL=page.html', command, 'wrap λ "legacy range test"'])
                run = subprocess.run(['bash', '-c', program], cwd=tmp,
                                     text=True, capture_output=True, check=False)
                matched = re.findall(r'case\d{4}(?=\t)', run.stdout)
                if (run.returncode != 0 or run.stderr or
                        sorted(matched) != sorted(expected * copies) or
                        bool(run.stdout) != warning or
                        (warning and 'Begin: legacy range test' not in run.stdout)):
                    failures.append(f"{name}: warning={warning}, exit={run.returncode}, "
                                    f"missing={sorted(set(expected) - set(matched))!r}, "
                                    f"unexpected={sorted(set(matched) - set(expected))!r}, "
                                    f"stdout={run.stdout!r}, stderr={run.stderr!r}")
    if failures:
        raise ValueError('\n'.join(failures))
    return len(positive), len(negative)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[2])
    parser.add_argument('--verbose', action='store_true')
    args = parser.parse_args()
    try:
        positive, negative = check(args.root)
    except (OSError, ValueError) as error:
        print(f'Range lint regression failure: {error}', file=sys.stderr)
        return 1
    if args.verbose:
        print(f'Range lints: {positive} positive / {negative} negative cases; '
              'both production commands and metadata globs passed.')
    return 0


if __name__ == '__main__':
    sys.exit(main())
