#!/usr/bin/env python3
"""Compile thermalphysics rejection cases against this checkout's runtime."""
from pathlib import Path
import os
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parents[1]
NODE_CASES = [('conduction slab,conduction width=0', 'Thermal slab dimensions must be positive'),
 ('composite wall,composite split=0', 'Composite split must lie strictly between 0 and 1'),
 ('composite wall,composite split=1', 'Composite split must lie strictly between 0 and 1'),
 ('convection surface,thermal fluid height=0', 'Convection lengths must be positive'),
 ('convection surface,thermal flow direction=0', 'Convection lengths must be positive'),
 ('cooling fin,fin thickness=2cm', 'Fin dimensions must satisfy'),
 ('cooling fin,fin length=.1cm', 'Fin dimensions must satisfy'),
 ('radiating body,radiation radius=0', 'Radiation radius and ray length must be positive'),
 ('radiating body,radiation ray length=0', 'Radiation radius and ray length must be positive'),
 ('radiating body,thermal flow direction=2', 'Radiation radius and ray length must be positive'),
 ('thermometer,thermometer height=.5cm', 'Thermometer requires positive dimensions'),
 ('thermometer,thermometer level=1.5', 'Thermometer requires positive dimensions'),
 ('thermometer,thermometer stem width=1cm', 'Thermometer requires positive dimensions'),
 ('calorimeter,calorimeter insulation=2cm', 'Calorimeter requires positive dimensions'),
 ('calorimeter,calorimeter level=1', 'Calorimeter requires positive dimensions'),
 ('expansion rod,thermal expansion ratio=0', 'Expansion rod lengths must be positive'),
 ('expansion rod,thermal expansion ratio=4', 'Expansion rod lengths must be positive'),
 ('expansion rod,expansion separation=.05cm', 'Expansion rod lengths must be positive')]
PIC_CASES = []


def main():
    env = os.environ.copy()
    env['TEXINPUTS'] = str(ROOT) + os.pathsep
    cases = [(r'\node[' + options + r'] (N) {};', diagnostic)
             for options, diagnostic in NODE_CASES] + PIC_CASES
    with tempfile.TemporaryDirectory(prefix='tikzphysics-thermalphysics-') as folder:
        work = Path(folder)
        for index, (body, diagnostic) in enumerate(cases):
            source = (r'\documentclass{article}\usepackage{tikzphysics}\begin{document}'
                      r'\begin{tikzpicture}' + body + r'\end{tikzpicture}\end{document}')
            (work / 'case.tex').write_text(source)
            proc = subprocess.run(
                ['pdflatex', '-interaction=nonstopmode', '-halt-on-error', 'case.tex'],
                cwd=work, env=env, capture_output=True, text=True, timeout=60)
            # TeX may hard-wrap a diagnostic inside a word.
            normalized = ''.join(proc.stdout.split())
            if proc.returncode == 0 or ''.join(diagnostic.split()) not in normalized:
                raise SystemExit(f'FAIL case {index}: {body}\n{proc.stdout[-2500:]}')
            print(f'PASS: rejected {body}')
    print(f'All {len(cases)} invalid-input cases rejected with the intended diagnostic.')


if __name__ == '__main__':
    main()
