#!/usr/bin/env python3
"""Quals for where the quals are ([FAC] stage 2, 2026-10-31; dreeves's README: "[FAC] Reorganize the files: quals and
search stuff in their own directories"): in quals/, each finding the repository's root by its own location, so that
each runs as it did at the root; and that the root's pages link files that are here ([FAC] stage 3a, 2026-10-31: the
finished searches into searches/, the proofs and certificates into proofs/); and that the search engine is in
engine/, importing nothing of the root's ([FAC] stage 3b, 2026-11-04).
Run: python3 -B quals/quals_layout.py [name ...]   (no arguments: all quals).

Each qual is a function q_*: a passing qual returns, a failing one raises.  Each qual's comment gives its replicata (the
setup) and expectata (what must happen); a failure's message or traceback gives the resultata (what happened instead)."""
import sys
sys.dont_write_bytecode = True
import os, re, subprocess, tempfile, time, traceback, urllib.parse
from concurrent.futures import ThreadPoolExecutor
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # the repository's root, above quals/
QUALS = os.path.join(HERE, 'quals')
PYLIB = os.path.join(HERE, 'scratch', 'lower24-design', 'beyond1000', 'pylib')   # fpylll, as the suites run with it
# A qual's module-level code run as `python3 FILE` runs it (its own directory first on sys.path), but under a name other
# than __main__, so that its quals do not run: its imports among that code.
IMPORT = ('import runpy, os, sys\n'
          'sys.path.insert(0, os.path.dirname(sys.argv[1]))\n'
          'runpy.run_path(sys.argv[1], run_name="quals_layout_import")\n')


def q_quals_are_in_quals():
    # Replicata: the names in the repository's root and in its quals/.
    # Expectata (2026-10-31): no file at the root named quals_*; in quals/ only quals: the suites
    # (*.py), the Node harnesses (*.cjs) and the data the stall quals read (quals_case_lp_stall.json), all named quals_*.
    # Resultata before the move: 66 more quals_* files at the root, and no quals/.
    # (2026-11-10, dreeves's README, [REF]: until then two stayed at the root, quals_proof384.py and
    # quals_proof384_page.py, which the 384 proof's own page linked beside it; that page is now a redirect.)
    # (2026-11-10, dreeves: "can you put READMEs in each directory": quals/ holds its README.md, which "in quals/ only
    # quals" made an error.  A file that is not a qual gets into quals/ on purpose, and a check that only something
    # done on purpose can fail is cut when it bites (dreeves, the same day, of a qual that forbade links to .txt files:
    # "if we link to a .txt then ipso facto we did it on purpose, right?").  What can happen by accident stays: a suite
    # or a harness whose name does not start with quals_, which whoever runs quals_* would never run.)
    root = sorted(n for n in os.listdir(HERE) if n.startswith('quals_'))
    assert root == [], root
    there = sorted(n for n in os.listdir(QUALS) if n.endswith(('.py', '.cjs')))
    assert len(there) > 60 and all(n.startswith('quals_') for n in there), there


def q_python_quals_import_from_anywhere():
    # Replicata: each quals/*.py but this one, its module-level code run (IMPORT) in a fresh Python whose working
    # directory and TMPDIR are an empty temporary directory, PYTHONPATH PYLIB.
    # Expectata: every one runs: each that imports the repository's modules puts the root on sys.path itself, by its own
    # location, and its quals/ neighbours import as Python puts its own directory first.
    # Resultata before the move: no quals/ to run them from.
    names = sorted(n for n in os.listdir(QUALS) if n.endswith('.py') and n != 'quals_layout.py')
    assert len(names) > 50, names
    with tempfile.TemporaryDirectory() as d:
        env = dict(os.environ, PYTHONPATH=PYLIB, TMPDIR=d)
        run = lambda n: subprocess.run([sys.executable, '-B', '-c', IMPORT, os.path.join(QUALS, n)], cwd=d, env=env,
                                       capture_output=True, text=True, timeout=900)
        with ThreadPoolExecutor(4) as pool:
            done = list(pool.map(run, names))
    bad = [(n, p.returncode, p.stderr[-1500:]) for n, p in zip(names, done) if p.returncode]
    assert not bad, bad


def q_harnesses_run_from_anywhere():
    # Replicata: each quals/*.cjs run by node in an empty temporary working directory.
    # Expectata: each passes (exit 0): each reads the page's files from the root, above its own directory.
    # Resultata before the move: the harnesses read index.html and page/ from the working directory.
    names = sorted(n for n in os.listdir(QUALS) if n.endswith('.cjs'))
    # (four since 2026-11-11, when the seven harnesses of the page's older views of a search went with those views;
    # eleven until then)
    assert len(names) >= 4, names
    with tempfile.TemporaryDirectory() as d:
        done = [subprocess.run(['node', os.path.join(QUALS, n)], cwd=d, capture_output=True, text=True, timeout=120)
                for n in names]
    bad = [(n, p.returncode, p.stdout[-800:] + p.stderr[-800:]) for n, p in zip(names, done) if p.returncode]
    assert not bad, bad


# The root's pages' links into this repository (see q_page_links_resolve): (a URL's prefix, whether what follows it
# names a file, or else a directory).
REPOSITORY = (('https://github.com/dreeves/equipow/blob/main/', True),
              ('https://raw.githubusercontent.com/dreeves/equipow/main/', True),
              ('https://github.com/dreeves/equipow/tree/main/', False), ('https://equipow.dreev.es/', True))


def q_page_links_resolve():
    # Replicata ([FAC] stage 3a, 2026-10-31: the finished searches into searches/, the proofs and certificates into
    # proofs/): each href and src of the root's two pages, index.html and proof384.html.
    # Expectata: each that names a file or directory of this repository names one that is here, its fragment and query
    # left out and its path percent-decoded: a relative one, a file under the root; one at a prefix of REPOSITORY, the
    # file or directory there under the root; the repository's page at GitHub, the root.  The links to GitHub are
    # checked against the files here, not over the network: they resolve once these files are pushed.
    # Resultata before the page's edits: index.html linked proof512.txt, record_gaps.wl and eight more at the root,
    # where they no longer were.
    urls = [u for page in ('index.html', 'proof384.html')
            for u in re.findall(r'\s(?:href|src)="([^"]*)"', open(os.path.join(HERE, page), encoding='utf-8').read())]
    path = lambda u: urllib.parse.unquote(u.split('#')[0].split('?')[0])
    named = ([(path(u), True) for u in urls if not re.match(r'[a-z]+:|#', u)] +
             [(path(u[len(p):]), file) for u in urls for p, file in REPOSITORY if u.startswith(p)] +
             [('', False) for u in urls if u == 'https://github.com/dreeves/equipow'])
    assert len(named) > 25, named
    missing = [(p, file) for p, file in named if not (os.path.isfile if file else os.path.isdir)(os.path.join(HERE, p))]
    assert not missing, missing


# The engine's files ([FAC] stage 3b, 2026-11-04): its modules, their compiled parts and sources, and the data its
# modules read beside themselves, in engine/ (q_engine_is_in_engine).
ENGINE = os.path.join(HERE, 'engine')
# The git-ignored .lattice288_prepared.json is left out, which a fresh clone lacks.
ENGINE_FILES = ('boxsplit.py', 'build_native.py', 'certbb.py', 'fanout.py', 'fastlp.py', '_fastlp.c',
                '_fastlp.cpython-313-darwin.so', 'focus.py', 'focus432.py', 'focus480.py', 'focus672.py',
                'focus432_certificates.json.gz', 'focus480_certificates.json.gz', 'lattice288.py', 'lattice288.log',
                'lattice288_journal.jsonl', 'native_bound.py', 'native_bound.cpp',
                '_native_bound.cpython-313-darwin.so', 'overnight_v5.py', 'reflection.py', 'reprove.py', 'residues.py',
                'width.py')


def q_engine_is_in_engine():
    # Replicata ([FAC] stage 3b, 2026-11-04; dreeves's README: "[FAC] Finish reorganizing the files: quals and search
    # stuff in their own directories"): the names in the repository's root and in its engine/.
    # Expectata: every one of ENGINE_FILES in engine/ and none of them at the root.
    # Resultata before the move: no engine/, all of them at the root.
    assert os.path.isdir(ENGINE), ENGINE
    assert not [n for n in ENGINE_FILES if not os.path.isfile(os.path.join(ENGINE, n))], os.listdir(ENGINE)
    assert not [n for n in ENGINE_FILES if os.path.exists(os.path.join(HERE, n))], ENGINE_FILES


def q_engine_imports_from_anywhere():
    # Replicata: each Python module of engine/, imported in a fresh Python whose working directory and TMPDIR are an
    # empty temporary directory, PYTHONPATH engine/ and PYLIB (fpylll, which lattice288 imports): not the root.
    # Expectata: every one imports, their pins of their compiled parts and sources holding: the engine imports nothing
    # of the root's, as its scripts and their workers run it.
    # Resultata before the move: no engine/ to import from.
    names = sorted(n[:-len('.py')] for n in os.listdir(ENGINE) if n.endswith('.py'))
    assert names == sorted(n[:-len('.py')] for n in ENGINE_FILES if n.endswith('.py')), names
    with tempfile.TemporaryDirectory() as d:
        env = dict(os.environ, PYTHONPATH=os.pathsep.join([ENGINE, PYLIB]), TMPDIR=d)
        run = lambda n: subprocess.run([sys.executable, '-B', '-c', f'import {n}'], cwd=d, env=env,
                                       capture_output=True, text=True, timeout=600)
        with ThreadPoolExecutor(4) as pool:
            done = list(pool.map(run, names))
    bad = [(n, p.returncode, p.stderr[-1500:]) for n, p in zip(names, done) if p.returncode]
    assert not bad, bad


def q_pagegen_and_searchwatch_import_from_anywhere():
    # Replicata (dreeves's README, [REF], 2026-11-10: "probably all the python scripts belong in a directory"; his names:
    # pagegen/ for what makes the page's data, searchwatch/ for what runs and watches the searches): each Python module
    # of those two directories, imported in a fresh Python whose working directory and TMPDIR are an empty temporary
    # directory, PYTHONPATH its own directory and PYLIB: not the root, and not the other directory.
    # Expectata: both directories hold modules, and every one imports: each finds the engine and the repository's root
    # by its own location, and its neighbours beside it, wherever it is run from.
    # Resultata before the move: neither directory; their fifteen scripts stood at the root.
    with tempfile.TemporaryDirectory() as d:
        runs = []
        for name in ('pagegen', 'searchwatch'):
            where = os.path.join(HERE, name)
            modules = sorted(n[:-len('.py')] for n in os.listdir(where) if n.endswith('.py'))
            assert modules, name
            env = dict(os.environ, PYTHONPATH=os.pathsep.join([where, PYLIB]), TMPDIR=d)
            runs += [(f'{name}/{m}', [sys.executable, '-B', '-c', f'import {m}'], env) for m in modules]
        run = lambda r: subprocess.run(r[1], cwd=d, env=r[2], capture_output=True, text=True, timeout=600)
        with ThreadPoolExecutor(4) as pool:
            done = list(pool.map(run, runs))
    bad = [(r[0], p.returncode, p.stderr[-1500:]) for r, p in zip(runs, done) if p.returncode]
    assert not bad, bad


def files():
    """The repository's files, each as its path from the root: those git has or would take (tracked, or untracked and
    not ignored) that are on disk: a file that was moved away stays in git's index until it is staged, and is not
    here."""
    listed = subprocess.run(['git', '-C', HERE, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],
                            capture_output=True, text=True, check=True).stdout.split('\0')
    return [f for f in listed if f and os.path.isfile(os.path.join(HERE, f))]


def directories():
    """The directories below the root that hold the repository's files (files()), each as its path from the root, in
    order."""
    dirs = sorted({'/'.join(f.split('/')[:i]) for f in files() for i in range(1, len(f.split('/')))})
    assert 'quals' in dirs, dirs          # the directory this suite is in
    return dirs


def readmes():
    """{directory: the text of its README.md}, for the directories below the root that have one.  The root's README
    is dreeves's, and no qual reads it."""
    return {d: open(os.path.join(HERE, d, 'README.md'), encoding='utf-8').read()
            for d in directories() if os.path.isfile(os.path.join(HERE, d, 'README.md'))}


def link_paths(text):
    """The paths that the markdown links of a README's text name, each from the README's own directory, as GitHub
    resolves them: of each link [text](target) whose target has no scheme (as https:) and is not a fragment of the
    README itself, the target, its fragment left out and its path percent-decoded."""
    return [urllib.parse.unquote(t.split('#')[0]) for t in re.findall(r'\]\(([^)\s]+)\)', text)
            if not re.match(r'[a-z]+:|#', t)]


def q_top_level_directories_have_a_readme():
    # Replicata (dreeves, 2026-11-10: "can you put READMEs in each directory, stating at the top that they're all you,
    # and documenting the directory's purpose?"; and, of a README in every subdirectory as well: "this looks idiotic;
    # we don't want a README for every single subdirectory, do we?"): the directories at the repository's root that
    # hold its files, hidden ones (.vscode) aside.
    # Expectata: each holds a README.md, so that a directory added there later does not go without one.
    # Resultata before: none of the eight did.
    top = [d for d in directories() if '/' not in d and not d.startswith('.')]
    missing = [d for d in top if d not in readmes()]
    assert top and not missing, (top, missing)


def q_readmes_name_their_subdirectories():
    # Replicata: each README.md below the root, and the directories of the repository's files right below its own.
    # Expectata (dreeves, 2026-11-10: "can't searches/README just list the subdirectories with one line each"): the
    # README names each of them, by its name and a slash at the start of a path ("cells/", not the end of
    # "x/cells/"), so that a directory added later, as a new search, does not go missing from the list.
    # Resultata before: searches/ and proofs/ had no README, so nothing listed the 19 searches.
    dirs, texts = directories(), readmes()
    unnamed = [(d, os.path.basename(e)) for d in texts for e in dirs if os.path.dirname(e) == d
               and not re.search(r'(?<![\w./-])' + re.escape(os.path.basename(e)) + '/', texts[d])]
    assert texts and not unnamed, unnamed


def q_readme_links_resolve():
    # Replicata: each README.md below the root, and its markdown links, [text](target), whose target has no scheme
    # (as https:) and is not a fragment of the README itself.
    # Expectata: each target, its fragment left out and its path percent-decoded, is a file or a directory here, from
    # the README's own directory, as GitHub resolves it: a file that a README lists as a link cannot be moved,
    # renamed or removed without the README following.
    # Resultata before: no README below the root held a link.
    # (2026-12-04: the links' parsing moved into link_paths, which q_readmes_link_their_files shares; the same links,
    # the same test.)
    links = [(d, p) for d, text in readmes().items() for p in link_paths(text)]
    assert links, 'no README below the root links a file'
    missing = [(d, p) for d, p in links if not os.path.exists(os.path.join(HERE, d, p))]
    assert not missing, missing


# The top-level directories whose README.md names files by a pattern, not each by a link, which
# q_readmes_link_their_files leaves out: pagedata/, whose README names by `N.hex` the file that pagegen/mstar.py adds
# there for each sequence of proofs/sym15.json and of proofs/symcenters.json, so that a new result needs no edit of the
# README; and quals/, whose README names its suites by `quals_*.py`.
PATTERNED = ('pagedata', 'quals')


def q_readmes_link_their_files():
    # Replicata (Gemini's bug report of 2026-12-04, sourcery.html#p1313, item 4: page/README.md "omits appendix.js and
    # says "eight scripts" (nine exist)", proofs/README.md "omits firstconditions.py, nestedmixed.py, and
    # sharedseam.py"): each directory at the repository's root that has a README.md, but those of PATTERNED; the
    # repository's files right in it (files()); and the links of its README.md (link_paths).
    # Expectata: each of those files but the README itself is the path of one of those links, as each directory right
    # below is named there (q_readmes_name_their_subdirectories), so that a file added later does not go missing from
    # its README.
    # Resultata before: page/appendix.js, proofs/firstconditions.py, proofs/nestedmixed.py and proofs/sharedseam.py
    # were the paths of no link.
    texts = readmes()
    tops = [d for d in texts if '/' not in d and d not in PATTERNED]
    linked = {os.path.normpath(os.path.join(d, p)) for d in tops for p in link_paths(texts[d])}
    unlinked = [f for f in files() if os.path.dirname(f) in tops and os.path.basename(f) != 'README.md' and f not in linked]
    assert set(PATTERNED) <= set(texts), (PATTERNED, sorted(texts))   # each a directory with a README, none left out by a slip
    assert not unlinked, unlinked


def main():
    names = sys.argv[1:] or [n for n in globals() if n.startswith('q_')]
    failed = 0
    for n in names:
        t0, c0 = time.time(), time.process_time()
        try:
            globals()[n]()
            # TODO: runner line; says the named qual passed, with its seconds and this process's CPU seconds
            print(f'Claude: "PASSED" {n} ({time.time() - t0:.1f} s, {time.process_time() - c0:.1f} CPU s)', flush=True)
        except Exception:
            failed += 1
            # TODO: runner line; says the named qual failed, with its seconds and this process's CPU seconds, followed by the traceback
            print(f'Claude: "FAILED" {n} ({time.time() - t0:.1f} s, {time.process_time() - c0:.1f} CPU s)\n' + traceback.format_exc(), flush=True)
    # TODO: runner summary; says how many quals passed out of how many
    print(f'Claude: "{len(names) - failed} of {len(names)} passed"')
    sys.exit(1 if failed else 0)


if __name__ == '__main__':
    main()
