import re

INTEGER = re.compile(r"[+-]?[0-9]+")

def parse_integer(text):
    cleaned = text.strip()
    if INTEGER.fullmatch(cleaned) is None:
        raise ValueError("Entier ASCII attendu")
    return int(cleaned)

assert parse_integer(" +42 ") == 42
assert INTEGER.fullmatch("42kg") is None


assert re.search("csv", "export_csv_2026").group() == "csv"
assert re.search("ab*", "audit").group() == "a"
assert all(re.fullmatch(r"ID-0*7", code) for code in ("ID-7", "ID-07", "ID-0007"))
assert re.fullmatch(r"ID-0*7", "ID-000") is None
assert re.fullmatch("ab+", "a") is None
assert re.fullmatch("ab?", "ab") is not None
assert re.fullmatch("(?:LOT){2,5}", "LOTLOT") is not None
assert re.search("[0-9]+", "statut=42").group() == "42"
assert re.match("[0-9]+", "statut=42") is None

code_lot = re.compile(r"LOT-[0-9]{2}(?:[ .-]?[0-9]{2}){2}")
for valeur in ("LOT-240103", "LOT-24 01 03", "LOT-24.01-03"):
    assert code_lot.fullmatch(valeur) is not None
for valeur in ("xLOT-240103", "LOT-24010", "LOT-240103" + chr(10)):
    assert code_lot.fullmatch(valeur) is None

ligne = "  lot    validé  "
assert re.sub(r" +", " ", ligne) == " lot validé "
assert ligne == "  lot    validé  "


texte = "LOT-42 et LOT-17"
assert re.sub(r"(LOT)-([0-9]+)", r"\g<2>/\g<1>", texte) == "42/LOT et 17/LOT"
identifiant = re.compile(r"id=(?P<id>[0-9]+)")
assert identifiant.sub(r"id[\g<id>]", "id=8 id=31") == "id[8] id[31]"
correspondance = identifiant.search("id=31")
assert correspondance.group("id") == "31"


assert re.search(r"^LOT", "LOT-42") is not None
assert re.search(r"^LOT", "xLOT-42") is None
assert re.search(r"42$", "LOT-42\n") is not None
assert re.fullmatch(r"LOT-42", "LOT-42\n") is None
assert re.fullmatch(r"ab*", "a") is not None
assert re.fullmatch(r"ab+", "abbb") is not None
assert re.fullmatch(r"ab?", "abb") is None
assert re.fullmatch(r"E{4}", "EEEE") is not None
assert re.fullmatch(r"E{2,4}", "EEE") is not None
assert re.fullmatch(r"E{0,5}", "") is not None
assert re.fullmatch(r"E{8,}", "E" * 8) is not None
assert re.fullmatch(r"[A-Z]{5}", "ABCDE") is not None
assert re.fullmatch(r"(?:LOT){2,5}", "LOTLOTLOT") is not None
assert re.fullmatch(r"\d", "٣") is not None
assert re.fullmatch(r"[0-9]", "٣") is None
correspondance = re.search(r"[0-9]+", "statut=42")
assert correspondance.group() == "42" and correspondance.span() == (7, 9)


motif_lot = re.compile(r"(?P<prefixe>LOT)-(?P<numero>[0-9]+)")
texte_source = "LOT-8 et LOT-31"
trouves = list(motif_lot.finditer(texte_source))
assert [(m.group("prefixe"), m.group("numero")) for m in trouves] == [("LOT", "8"), ("LOT", "31")]
assert trouves[0].group(0) == "LOT-8" and trouves[0].group(2) == "8"
assert motif_lot.sub(r"\g<numero>/\g<prefixe>", texte_source) == "8/LOT et 31/LOT"
assert texte_source == "LOT-8 et LOT-31"
assert motif_lot.search("sans identifiant") is None
assert motif_lot.fullmatch("LOT-8") is not None
assert motif_lot.fullmatch("LOT-8 suffixe") is None

assert code_lot.fullmatch("LOT-240103") is not None
assert code_lot.fullmatch("LOT-24.01-03") is not None
assert code_lot.fullmatch("LOT-24.01-03-extra") is None
assert re.search(r"(?:LOT){2,5}", "avant LOTLOT après").group() == "LOTLOT"
assert re.search(r"[A-Z]{5}", "REF=ABCDE-12").group() == "ABCDE"
assert re.search(r"[0-9]+", "source=42").span() == (7, 9)

ligne_brute = "source=8;source=31;source=127"
ligne_normalisee = re.sub(r"source=(?P<id>[0-9]+)", r"source[\g<id>]", ligne_brute)
assert ligne_normalisee == "source[8];source[31];source[127]"
assert ligne_brute == "source=8;source=31;source=127"
code_compose = re.compile(r"LOT-([0-9]{2})([0-9]{2})([0-9]{2})")
assert code_compose.fullmatch("LOT-240103").groups() == ("24", "01", "03")
assert code_compose.sub(r"LOT-\g<1>/\g<2>/\g<3>", "LOT-240103") == "LOT-24/01/03"

from datetime import date

motif_date = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
assert motif_date.fullmatch("2024-02-29") is not None
assert date.fromisoformat("2024-02-29").day == 29
assert motif_date.fullmatch("2024-02-30") is not None
try:
    date.fromisoformat("2024-02-30")
except ValueError:
    pass
else:
    raise AssertionError("La date impossible doit être refusée")

chiffre_unicode = "١"
assert re.fullmatch(r"\d", chiffre_unicode) is not None
assert re.fullmatch(r"[0-9]", chiffre_unicode) is None
assert re.fullmatch(r"\d", chiffre_unicode, flags=re.ASCII) is None
assert re.fullmatch(r"[0-9]", "1") is not None

champ_avec_saut = "12\n"
assert re.search(r"^[0-9]+$", champ_avec_saut).group() == "12"
assert re.fullmatch(r"[0-9]+", champ_avec_saut) is None
assert re.fullmatch(r"[0-9]+", "12") is not None

code_lot_coherent = re.compile(
    r"LOT-(?:[0-9]{6}|[0-9]{2}(?P<sep>[ .-])[0-9]{2}(?P=sep)[0-9]{2})"
)
for valeur in ("LOT-240103", "LOT-24.01.03", "LOT-24 01 03", "LOT-24-01-03"):
    assert code_lot_coherent.fullmatch(valeur) is not None
for valeur in ("LOT-24.01-03", "LOT-24.0103", "LOT-2401.03", "xLOT-240103"):
    assert code_lot_coherent.fullmatch(valeur) is None

import re
assert re.fullmatch(r"[A-Z]+", "lot", re.IGNORECASE)
assert re.fullmatch(r"[A-Z]+", "K", re.IGNORECASE)
assert re.fullmatch(r"[A-Z]+", "K", re.IGNORECASE | re.ASCII) is None
assert re.fullmatch(r"[A-Z]+", "LOT", re.IGNORECASE | re.ASCII)

import re
valeur_source = r"\n"
assert re.sub("MARQUEUR", valeur_source, "MARQUEUR") == "\n"
assert re.sub("MARQUEUR", lambda match: valeur_source, "MARQUEUR") == r"\n"

donnee_brute = b"LOT-2026"
identifiant_texte = donnee_brute.decode("utf-8")
assert re.fullmatch(r"LOT-[0-9]{4}", identifiant_texte)
assert re.fullmatch(rb"LOT-[0-9]{4}", donnee_brute)
try:
    re.fullmatch(r"LOT-[0-9]{4}", donnee_brute)
except TypeError:
    pass
else:
    raise AssertionError("Un motif texte ne peut pas traiter des octets")
try:
    bytes([255]).decode("utf-8")
except UnicodeDecodeError:
    pass
else:
    raise AssertionError("Un octet UTF-8 invalide doit être signalé")

import re

motif_source = r"[A-Z]{3}"
assert re.fullmatch(motif_source, "etl") is None
assert re.fullmatch(motif_source, "etl", re.IGNORECASE)
assert re.fullmatch(motif_source, "ETK", re.IGNORECASE)
assert re.fullmatch(motif_source, "ETK", re.IGNORECASE | re.ASCII) is None
assert re.fullmatch(motif_source, "etl", re.IGNORECASE | re.ASCII)

def saisir_code_lot(lire=input, afficher=print):
    motif = re.compile(r"LOT-[0-9]{2}(?:[ .-]?[0-9]{2}){2}")
    while True:
        try:
            valeur = lire("Code du lot : ")
        except EOFError:
            return None
        if motif.fullmatch(valeur):
            return valeur
        afficher("Format attendu : LOT- suivi de trois groupes de deux chiffres.")

reponses = iter(["LOT-24", "LOT-24.01-03"])
messages = []
assert saisir_code_lot(lambda invite: next(reponses), messages.append) == "LOT-24.01-03"
assert messages == ["Format attendu : LOT- suivi de trois groupes de deux chiffres."]

def entree_fermee(invite):
    raise EOFError

assert saisir_code_lot(entree_fermee, messages.append) is None
# Dans un terminal : code_choisi = saisir_code_lot()

motif_identifiant_lot = re.compile(r"LOT-[0-9]{4}")

def demander_identifiant(lire=input, signaler=print):
    while True:
        try:
            saisie = lire("Identifiant du lot : ")
        except EOFError:
            return None
        if motif_identifiant_lot.fullmatch(saisie):
            return saisie
        signaler("Format attendu : LOT- suivi de quatre chiffres ASCII")

reponses_test = iter(["LOT-12", "xLOT-2026", "LOT-2026"])
messages_test = []
assert demander_identifiant(lambda invite: next(reponses_test), messages_test.append) == "LOT-2026"
assert len(messages_test) == 2

def fin_de_saisie(invite):
    raise EOFError

assert demander_identifiant(fin_de_saisie, messages_test.append) is None

journal_lots = "entrée LOT-8 ; entrée LOT-31"
assert re.findall(r"LOT-[0-9]+", journal_lots) == ["LOT-8", "LOT-31"]
assert re.findall(r"LOT-([0-9]+)", journal_lots) == ["8", "31"]
assert re.findall(r"(LOT)-([0-9]+)", journal_lots) == [("LOT", "8"), ("LOT", "31")]
assert re.findall(r"(?:LOT)-[0-9]+", journal_lots) == ["LOT-8", "LOT-31"]
correspondances = list(re.finditer(r"LOT-([0-9]+)", journal_lots))
assert [(m.group(0), m.group(1), m.span()) for m in correspondances] == [
    ("LOT-8", "8", (7, 12)), ("LOT-31", "31", (22, 28))
]

motif_ancien_lot = re.compile(r"LOT-0[0-9](?:[ .-]?[0-9]{2}){4}")
for identifiant in ("LOT-0123456789", "LOT-01 23 45 67 89", "LOT-01.23-45 67.89"):
    assert motif_ancien_lot.fullmatch(identifiant) is not None
for identifiant in ("LOT-1123456789", "LOT-012345678", "LOT-01234567890", "xLOT-0123456789"):
    assert motif_ancien_lot.fullmatch(identifiant) is None
