"""Vuelve a correr los comandos que aparecen en los apuntes y en las diapositivas, y
comprueba que el código citado existe de verdad en los archivos públicos de esta carpeta."""
import os
import pathlib
import platform
import re
import subprocess
import unittest

try:
    import pty
except ImportError:
    pty = None

HERE = pathlib.Path(__file__).parent
ROOT = HERE.parent.parent
NOTES = ROOT / "notes" / "week-04.md"
SLIDES = ROOT / "slides" / "week-04.tex"
# Antes de un bloque cuya salida cambia con la máquina, como los tiempos. No se compara.
SYSTEM_DEPENDENT = "<!-- depende del sistema -->"
# Antes de un informe de ASan o de un error del compilador. Puede omitir líneas, pero no
# cambiarlas ni reordenarlas. Las direcciones y los números de proceso no se comparan.
REPORT = "<!-- informe recortado -->"
REPORT_MACHINE = "aarch64"


def normalize(text):
    # Según el idioma del entorno, g++ usa comillas tipográficas o rectas.
    return text.replace("‘", "'").replace("’", "'")


def run_shell(command):
    done = subprocess.run(["bash", "-c", command], cwd=HERE, text=True, encoding="utf-8",
                          stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT, timeout=120)
    return normalize(done.stdout)


def clean_lines(text):
    return [line.rstrip() for line in text.splitlines()]


def stable(line):
    """Quita de una línea de informe lo que cambia en cada corrida."""
    line = re.sub(r"0x[0-9a-f]+", "ADDR", line.strip())
    line = re.sub(r"BuildId: [0-9a-f]+", "BuildId: ID", line)
    return re.sub(r"==\d+==", "==N==", line)


def split_commands(lines):
    pairs = []
    for line in lines:
        if line.startswith("$ "):
            pairs.append((line[2:], []))
        elif pairs:
            pairs[-1][1].append(normalize(line.rstrip()))
    return pairs


def note_blocks(language):
    """Devuelve (líneas, marca) de cada bloque de los apuntes."""
    blocks, current, mark, previous = [], None, "", ""
    for raw in NOTES.read_text(encoding="utf-8").splitlines():
        line = re.sub(r"^> ?", "", raw)
        if current is None:
            if line.strip() == "```" + language:
                current, mark = [], previous.strip()
            elif line.strip():
                previous = line
        elif line.strip() == "```":
            blocks.append((current, mark))
            current = None
        else:
            current.append(line)
    return blocks


def slide_blocks(environments):
    text = SLIDES.read_text(encoding="utf-8")
    pattern = r"\\begin\{(?:%s)\}[^\n]*\n(.*?)\\end\{(?:%s)\}" % (environments, environments)
    return [match.group(1).splitlines() for match in re.finditer(pattern, text, re.S)]


def public_code_lines():
    """Solo archivos públicos: citar la solución del laboratorio hace fallar la prueba."""
    sources = list(HERE.glob("*.cpp")) + list(HERE.glob("*.h"))
    sources += list((HERE / "errors").glob("*.cpp"))
    sources += list((HERE / "lab").glob("*.cpp")) + list((HERE / "lab").glob("*.h"))
    lines = set()
    for source in sources:
        lines.update(line.strip() for line in source.read_text(encoding="utf-8").splitlines())
    return lines


class Base(unittest.TestCase):
    def assert_in_order(self, command, expected, actual):
        wanted = [stable(line) for line in expected if line.strip() and line.strip() != "..."]
        real = [stable(line) for line in actual]
        position = 0
        for line in wanted:
            with self.subTest(command=command, line=line):
                found = [i for i in range(position, len(real)) if real[i] == line]
                self.assertTrue(found, f"no aparece en la salida real: {line}")
                if found:
                    position = found[0] + 1


class NotesAreTrue(Base):
    @unittest.skipUnless(NOTES.exists(), "faltan los apuntes")
    def test_terminal_blocks(self):
        checked = 0
        for lines, mark in note_blocks("text"):
            if not lines or not lines[0].startswith("$ ") or mark == REPORT:
                continue
            for command, expected in split_commands(lines):
                actual = clean_lines(run_shell(command))
                checked += 1
                if mark != SYSTEM_DEPENDENT:
                    with self.subTest(command=command):
                        self.assertEqual(actual, expected)
        self.assertGreater(checked, 8)

    @unittest.skipUnless(NOTES.exists(), "faltan los apuntes")
    @unittest.skipUnless(platform.machine() == REPORT_MACHINE, "los informes son de aarch64")
    def test_reports(self):
        checked = 0
        for lines, mark in note_blocks("text"):
            if mark != REPORT:
                continue
            for command, expected in split_commands(lines):
                self.assert_in_order(command, expected, clean_lines(run_shell(command)))
                checked += 1
        self.assertGreater(checked, 2)

    @unittest.skipUnless(NOTES.exists(), "faltan los apuntes")
    def test_code_blocks_are_public_code(self):
        known = public_code_lines()
        for lines, _ in note_blocks("cpp"):
            for line in lines:
                if line.strip() and line.strip() != "...":
                    with self.subTest(line=line):
                        self.assertIn(line.strip(), known)

    @unittest.skipUnless(NOTES.exists(), "faltan los apuntes")
    def test_links_exist(self):
        text = NOTES.read_text(encoding="utf-8")
        for target in re.findall(r"\]\((\.\.?/[^)#\s]+)", text):
            with self.subTest(link=target):
                self.assertTrue((NOTES.parent / target).exists())

    @unittest.skipUnless(NOTES.exists(), "faltan los apuntes")
    def test_the_counts_in_the_review_questions(self):
        text = NOTES.read_text(encoding="utf-8")
        self.assertIn("1 + 2 + 4 + 8 = 15", text)
        output = run_shell("build/ring_trace")
        self.assertIn("e0->6 e1->7 e2->0 e3->1", output)


class SlidesAreTrue(Base):
    @unittest.skipUnless(SLIDES.exists(), "faltan las diapositivas")
    def test_program_output(self):
        for block in slide_blocks("terminal|salida|informe"):
            for command, expected in split_commands(block):
                self.assert_in_order(command, expected, clean_lines(run_shell(command)))

    @unittest.skipUnless(SLIDES.exists(), "faltan las diapositivas")
    def test_code_blocks_are_public_code(self):
        known = public_code_lines()
        for block in slide_blocks("codigochico|codigomini"):
            for line in block:
                if line.strip() and line.strip() != "...":
                    with self.subTest(line=line):
                        self.assertIn(line.strip(), known)


if __name__ == "__main__":
    unittest.main()
