import argparse
import subprocess
import sys

parser = argparse.ArgumentParser(description="Contrôler un lot")
parser.add_argument("--limit", type=int, default=100)
args = parser.parse_args(["--limit", "25"])
assert args.limit == 25
result = subprocess.run(
    [sys.executable, "-c", "print(2 + 3)"],
    capture_output=True, text=True, timeout=5, check=True,
)
assert result.stdout.strip() == "5"


from contextlib import redirect_stdout, redirect_stderr
from io import StringIO
import json

sortie, diagnostic = StringIO(), StringIO()
with redirect_stdout(sortie), redirect_stderr(diagnostic):
    print(json.dumps({"lignes_valides": 3}))
    print("Une ligne rejetée", file=sys.stderr)
assert json.loads(sortie.getvalue()) == {"lignes_valides": 3}
assert diagnostic.getvalue().strip() == "Une ligne rejetée"


import getopt

arret = {"demande": False}
def demander_arret(numero_signal, frame):
    arret["demande"] = True

demander_arret(None, None)  # Test de la fonction, sans envoyer de signal.
assert arret["demande"] is True

options, chemins = getopt.getopt(
    ["--nombre", "5", "ventes janvier.csv"], "hn:", ["nombre=", "help"]
)
limite = None
for option, valeur in options:
    if option in ("-n", "--nombre"):
        limite = int(valeur)
assert limite == 5 and chemins == ["ventes janvier.csv"]
options_courtes, _ = getopt.getopt(["-n", "3"], "hn:", ["nombre=", "help"])
assert options_courtes == [("-n", "3")]
try:
    getopt.getopt(["--nombre"], "hn:", ["nombre=", "help"])
except getopt.GetoptError:
    pass
else:
    raise AssertionError("Option sans valeur acceptée")


def lire_options(arguments):
    options, chemins = getopt.getopt(arguments, "ho:v", ["help", "output="])
    config = {"aide": False, "sortie": None, "detail": False}
    for option, valeur in options:
        if option in ("-h", "--help"):
            config["aide"] = True
        elif option == "-v":
            config["detail"] = True
        elif option in ("-o", "--output"):
            config["sortie"] = valeur
    return config, chemins

configuration, fichiers = lire_options(["-v", "--output", "rapport.json", "ventes.csv"])
assert configuration == {"aide": False, "sortie": "rapport.json", "detail": True}
assert fichiers == ["ventes.csv"]
assert lire_options(["-h"])[0]["aide"] is True
try:
    lire_options(["--inconnue"])
except getopt.GetoptError:
    pass
else:
    raise AssertionError("Option inconnue acceptée")

enfant = subprocess.run(
    [sys.executable, "-c", "print(3)"],
    capture_output=True, text=True, check=True, timeout=5,
)
assert int(enfant.stdout.strip()) == 3
try:
    subprocess.run([sys.executable, "-c", "raise SystemExit(4)"],
                   capture_output=True, check=True, timeout=5)
except subprocess.CalledProcessError as erreur:
    assert erreur.returncode == 4
else:
    raise AssertionError("Échec du processus non détecté")


flux_precedent = sys.stdout
capture = StringIO()
try:
    with redirect_stdout(capture):
        assert sys.stdout.write("lot") == 3
        print(" validé")
        raise ValueError("fin du test")
except ValueError:
    pass
assert sys.stdout is flux_precedent
assert capture.getvalue() == "lot validé\n"

entree = StringIO("lot-1\nlot-2\n")
assert entree.readline().strip() == "lot-1"
assert entree.read().strip() == "lot-2"

try:
    sys.exit(2)
except SystemExit as sortie:
    assert sortie.code == 2
else:
    raise AssertionError("sys.exit doit lever SystemExit")


arguments = ["ventes janvier.csv", "-v"]
options_classiques, restants_classiques = getopt.getopt(arguments, "v")
import os
from unittest.mock import patch

with patch.dict(os.environ):
    os.environ.pop("POSIXLY_CORRECT", None)
    options_gnu, restants_gnu = getopt.gnu_getopt(arguments, "v")
with patch.dict(os.environ, {"POSIXLY_CORRECT": "1"}):
    options_posix, restants_posix = getopt.gnu_getopt(arguments, "v")
assert options_classiques == [] and restants_classiques == arguments
assert options_gnu == [("-v", "")] and restants_gnu == ["ventes janvier.csv"]
assert options_posix == [] and restants_posix == arguments

commande = [sys.executable, "-c", "import json, sys; print(json.dumps(sys.argv[1:]))", "ventes janvier.csv", "25"]
resultat_arguments = subprocess.run(commande, capture_output=True, text=True, check=True, timeout=5)
assert json.loads(resultat_arguments.stdout) == ["ventes janvier.csv", "25"]

def choisir_action(arguments):
    if len(arguments) != 1 or arguments[0] not in ("valider", "charger"):
        return 2, "action attendue : valider ou charger"
    return 0, arguments[0]

assert choisir_action(["valider"]) == (0, "valider")
assert choisir_action([])[0] == 2 and choisir_action(["inconnue"])[0] == 2
assert choisir_action(["valider", "inattendu"])[0] == 2


try:
    subprocess.run([sys.executable, "-c", "import time; time.sleep(1)"],
                   capture_output=True, timeout=0.05, check=True)
except subprocess.TimeoutExpired:
    pass
else:
    raise AssertionError("Le délai du processus doit être dépassé")

sortie_precedente = sys.stdout
capture_temporaire = StringIO()
try:
    with redirect_stdout(capture_temporaire):
        nombre_ecrit = sys.stdout.write("lot prêt")
        raise ValueError("arrêt simulé")
except ValueError:
    pass
else:
    raise AssertionError("L'erreur simulée doit se propager")
assert nombre_ecrit == len("lot prêt")
assert capture_temporaire.getvalue() == "lot prêt"
assert sys.stdout is sortie_precedente
try:
    sys.exit(3)
except SystemExit as fin:
    assert fin.code == 3
else:
    raise AssertionError("sys.exit doit lever SystemExit")

for arguments_invalides in (["--nombre"], ["--inconnue"]):
    try:
        getopt.getopt(arguments_invalides, "n:", ["nombre="])
    except getopt.GetoptError:
        pass
    else:
        raise AssertionError("L'option invalide doit être signalée")
options_avant_chemin, arguments_restants = getopt.getopt(
    ["lot.csv", "--nombre", "5"], "n:", ["nombre="]
)
assert options_avant_chemin == []
assert arguments_restants == ["lot.csv", "--nombre", "5"]

from contextlib import redirect_stdout
from io import StringIO

rapport_capture = StringIO()
diagnostic_capture = StringIO()
with redirect_stdout(rapport_capture):
    print("début rapport")
    with redirect_stdout(diagnostic_capture):
        print("diagnostic local")
    print("fin rapport")
assert rapport_capture.getvalue().splitlines() == ["début rapport", "fin rapport"]
assert diagnostic_capture.getvalue().splitlines() == ["diagnostic local"]

import getopt

def lire_limite(arguments):
    options, restants = getopt.getopt(arguments, "hn:", ["number=", "help"])
    limite = None
    for nom, valeur in options:
        if nom in ("-n", "--number"):
            limite = int(valeur)
    return limite, restants

assert lire_limite(["-n", "5", "lot.csv"]) == (5, ["lot.csv"])
assert lire_limite(["--number", "5", "lot.csv"]) == (5, ["lot.csv"])

etat_execution = {"arret": False}
journal_lots = []
def signaler_arret(numero_signal, frame):
    etat_execution["arret"] = True

try:
    for lot in ("lot-1", "lot-2"):
        if etat_execution["arret"]:
            break
        journal_lots.append(lot)
        signaler_arret(None, None)  # Simulation après le premier lot.
finally:
    journal_lots.append("ressources fermées")

assert journal_lots == ["lot-1", "ressources fermées"]
assert etat_execution["arret"] is True

from tempfile import TemporaryFile

with TemporaryFile(mode="w+t", encoding="utf-8") as sortie_lots:
    resultat_enfant = subprocess.run(
        [sys.executable, "-c", "print('lot-1'); print('lot-2')"],
        stdout=sortie_lots, stderr=subprocess.PIPE, text=True, check=True, timeout=5,
    )
    sortie_lots.seek(0)
    assert [ligne.strip() for ligne in sortie_lots] == ["lot-1", "lot-2"]
    assert resultat_enfant.stderr == ""

import argparse

analyseur_chemin = argparse.ArgumentParser()
analyseur_chemin.add_argument("source")
assert analyseur_chemin.parse_args(["--", "-lot.csv"]).source == "-lot.csv"
assert analyseur_chemin.parse_args(["ventes janvier.csv"]).source == "ventes janvier.csv"

import argparse
from contextlib import redirect_stderr
from io import StringIO

souple = argparse.ArgumentParser()
souple.add_argument("--limit", type=int)
assert souple.parse_args(["--lim", "5"]).limit == 5

strict = argparse.ArgumentParser(allow_abbrev=False)
strict.add_argument("--limit", type=int)
assert strict.parse_args(["--limit", "5"]).limit == 5
diagnostic_option = StringIO()
try:
    with redirect_stderr(diagnostic_option):
        strict.parse_args(["--lim", "5"])
except SystemExit as erreur:
    assert erreur.code != 0
else:
    raise AssertionError("L'option abrégée doit être refusée")
assert "--lim" in diagnostic_option.getvalue()

options, chemins = getopt.getopt(["-n", "5", "--", "-lot.csv"], "n:")
assert options == [("-n", "5")]
assert chemins == ["-lot.csv"]

import getopt

options, chemins = getopt.getopt(["--nomb", "5", "lots.csv"], "", ["nombre="])
assert options == [("--nombre", "5")]
assert chemins == ["lots.csv"]
try:
    getopt.getopt(["--nom", "5"], "", ["nombre=", "nommer="])
except getopt.GetoptError:
    pass
else:
    raise AssertionError("Le préfixe ambigu doit être refusé")
options, _ = getopt.getopt(["--nombre", "5"], "", ["nombre=", "nommer="])
assert options == [("--nombre", "5")]
