#!/usr/bin/env python3
"""Pruebas de scripts/changelog_pendientes.py contra repos git temporales (#25177).

Correr:  python3 scripts/test_changelog_pendientes.py
No toca la red ni el repo real: cada caso arma su propio repositorio.
"""
import os
import subprocess
import sys
import tempfile
import unittest

AQUI = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, AQUI)
import changelog_pendientes as cp  # noqa: E402


def sh(cwd, *args):
    env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t")
    r = subprocess.run(args, cwd=cwd, capture_output=True, text=True, env=env)
    if r.returncode != 0:
        raise RuntimeError(f"{args}: {r.stderr}")
    return r.stdout.strip()


class Repo:
    def __init__(self):
        self.dir = tempfile.mkdtemp(prefix="cl-test-")
        sh(self.dir, "git", "init", "-q", "-b", "main")
        os.makedirs(os.path.join(self.dir, "app/config"))
        self.n = 0
        self.escribir("app/config/config.yml", "version: 0\n")
        self.escribir("changelog.md", "")
        sh(self.dir, "git", "add", "-A")
        sh(self.dir, "git", "commit", "-q", "-m", "base")

    def escribir(self, ruta, texto):
        with open(os.path.join(self.dir, ruta), "w") as f:
            f.write(texto)

    def corte(self):
        """Un corte como el real: rama lateral que toca config.yml y merge a main."""
        self.n += 1
        rama = f"hot{self.n}"
        sh(self.dir, "git", "checkout", "-q", "-b", rama)
        self.escribir("app/config/config.yml", f"version: {self.n}\n")
        sh(self.dir, "git", "commit", "-qam", f"bump {self.n}")
        sh(self.dir, "git", "checkout", "-q", "main")
        sh(self.dir, "git", "merge", "-q", "--no-ff", "-m", f"merge {self.n}", rama)
        return sh(self.dir, "git", "rev-parse", "HEAD")

    def otro(self):
        """Un merge a main que NO toca config.yml."""
        self.n += 1
        rama = f"otro{self.n}"
        sh(self.dir, "git", "checkout", "-q", "-b", rama)
        self.escribir(f"x{self.n}.txt", "x")
        sh(self.dir, "git", "add", "-A")
        sh(self.dir, "git", "commit", "-qm", f"x{self.n}")
        sh(self.dir, "git", "checkout", "-q", "main")
        sh(self.dir, "git", "merge", "-q", "--no-ff", "-m", f"merge otro {self.n}", rama)

    def cubrir(self, *shas):
        """changelog.md con una entrada por SHA; el ultimo de la lista queda arriba (mas nuevo)."""
        texto = ""
        for sha in shas:
            texto = f"<!-- changelog-cut:{sha} -->\n## Version x\n\n" + texto
        self.escribir("changelog.md", texto)

    def pendientes(self):
        cwd = os.getcwd()
        os.chdir(self.dir)
        try:
            return cp.pendientes("HEAD")
        finally:
            os.chdir(cwd)


class PruebasPendientes(unittest.TestCase):
    def test_nada_pendiente_si_el_ultimo_corte_tiene_marcador(self):
        r = Repo()
        a = r.corte()
        b = r.corte()
        r.cubrir(a, b)
        self.assertEqual(r.pendientes(), [])

    def test_dos_cortes_omitidos_salen_del_mas_viejo_al_mas_nuevo(self):
        r = Repo()
        a = r.corte()
        r.cubrir(a)
        b = r.corte()
        c = r.corte()
        self.assertEqual(r.pendientes(), [b, c])

    def test_merges_que_no_tocan_config_no_son_cortes(self):
        r = Repo()
        a = r.corte()
        r.cubrir(a)
        r.otro()
        b = r.corte()
        r.otro()
        self.assertEqual(r.pendientes(), [b])

    def test_marcador_de_la_punta_de_un_push_no_duplica_el_corte(self):
        # Un push con varios commits: la entrada guarda la PUNTA, que no toca config.yml.
        r = Repo()
        corte = r.corte()
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertNotEqual(corte, punta)
        r.cubrir(punta)
        self.assertEqual(r.pendientes(), [])

    def test_sin_ningun_marcador_valido_no_adivina(self):
        r = Repo()
        r.corte()
        r.escribir("changelog.md", "## Version vieja sin marcador\n")
        with self.assertRaises(cp.SinDecision):
            r.pendientes()

    def test_marcador_de_un_commit_que_no_es_ancestro_se_ignora(self):
        # Un marcador de una rama lateral (nacida del corte MAS NUEVO) no es punto base:
        # si se usara, `ajeno..HEAD` daria [] y se perderia el corte b.
        r = Repo()
        a = r.corte()
        b = r.corte()
        sh(r.dir, "git", "checkout", "-q", "-b", "lateral")
        r.escribir("l.txt", "l")
        sh(r.dir, "git", "add", "-A")
        sh(r.dir, "git", "commit", "-qm", "lateral")
        ajeno = sh(r.dir, "git", "rev-parse", "HEAD")
        sh(r.dir, "git", "checkout", "-q", "main")
        r.cubrir(a, ajeno)  # el de arriba es el ajeno; debe caer al siguiente valido (a)
        self.assertEqual(r.pendientes(), [b])

    def test_demasiados_pendientes_se_niega(self):
        r = Repo()
        a = r.corte()
        r.cubrir(a)
        for _ in range(cp.MAXIMO + 1):
            r.corte()
        with self.assertRaises(cp.SinDecision):
            r.pendientes()


class PruebasPunta(unittest.TestCase):
    def _extender(self, r, shas, antes, punta):
        cwd = os.getcwd()
        os.chdir(r.dir)
        try:
            return cp.extender_a_la_punta(shas, antes, punta)
        finally:
            os.chdir(cwd)

    def test_push_con_commits_despues_del_de_config_termina_en_la_punta(self):
        r = Repo()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        corte = r.corte()
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [corte], antes, punta), [punta])

    def test_solo_cambia_el_corte_mas_nuevo(self):
        r = Repo()
        a = r.corte()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        b = r.corte()
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [a, b], antes, punta), [a, punta])

    def test_push_que_no_toco_config_no_se_extiende(self):
        # Ej.: el push del merge del PR de changelog: la punta trae codigo que no es del corte.
        r = Repo()
        corte = r.corte()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [corte], antes, punta), [corte])

    def test_sin_dato_del_push_no_se_extiende(self):
        r = Repo()
        corte = r.corte()
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        for antes in ("", "0" * 40):
            self.assertEqual(self._extender(r, [corte], antes, punta), [corte])

    def test_corte_que_ya_estaba_antes_del_push_no_se_extiende(self):
        r = Repo()
        corte = r.corte()
        r.otro()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        r.otro()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [corte], antes, punta), [corte])


    def test_corte_anterior_al_push_no_se_extiende_aunque_el_push_toque_config(self):
        # El push cambio config.yml (corte b) pero el pendiente mas nuevo recibido es `a`,
        # que ya estaba antes del push: no se le puede poner la punta de OTRO corte.
        r = Repo()
        a = r.corte()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        r.corte()
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [a], antes, punta), [a])

    def test_push_que_deja_config_igual_no_se_extiende(self):
        # El corte entra y se revierte dentro del mismo push: el diff del push sobre
        # config.yml es vacio, asi que la punta no se le asigna.
        r = Repo()
        antes = sh(r.dir, "git", "rev-parse", "HEAD")
        corte = r.corte()
        r.escribir("app/config/config.yml", "version: 0\n")
        sh(r.dir, "git", "commit", "-qam", "revierte config")
        punta = sh(r.dir, "git", "rev-parse", "HEAD")
        self.assertEqual(self._extender(r, [corte], antes, punta), [corte])


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