from pathlib import PureWindowsPath, PurePosixPath

windows = PureWindowsPath("project") / "data" / "input.csv"
unix = PurePosixPath("project") / "data" / "input.csv"
assert windows.name == unix.name == "input.csv"
print("Commande locale : python -m mon_package.audit")


source_latin1 = ("# coding: latin-1" + chr(10) + "message = 'café'").encode("latin-1")
namespace = {}
exec(compile(source_latin1, "exemple.py", "exec"), namespace)
assert namespace["message"] == "café"


source_utf8 = "statut = 'lot validé'".encode("utf-8")
contexte_utf8 = {}
exec(compile(source_utf8, "controle_lot.py", "exec"), contexte_utf8)
assert contexte_utf8["statut"] == "lot validé"
source_latin1_sans_declaration = "message = 'café'".encode("latin-1")
try:
    compile(source_latin1_sans_declaration, "ancien.py", "exec")
except SyntaxError:
    pass
else:
    raise AssertionError("Le source Latin-1 doit déclarer son encodage")
assert namespace["message"] == "café"

from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess
import sys

with TemporaryDirectory() as dossier_script:
    script = Path(dossier_script) / "controle_lot.py"
    script.write_text("statut = 'validé'\nprint(len(statut))\n", encoding="utf-8")
    resultat = subprocess.run(
        [sys.executable, str(script)], capture_output=True,
        text=True, encoding="utf-8", check=True,
    )
    assert resultat.stdout.strip() == "6"
    assert resultat.returncode == 0

from contextlib import redirect_stdout
from io import StringIO

code_module = """def compter_lignes(lignes):
    return len(lignes)

if __name__ == '__main__':
    print(compter_lignes(['lot-A', 'lot-B']))
"""
sortie_module = StringIO()
avec_nom_module = {"__name__": "controle_lot"}
with redirect_stdout(sortie_module):
    exec(code_module, avec_nom_module)
assert sortie_module.getvalue() == ""
assert avec_nom_module["compter_lignes"](["A"]) == 1
sortie_programme = StringIO()
with redirect_stdout(sortie_programme):
    exec(code_module, {"__name__": "__main__"})
assert sortie_programme.getvalue().strip() == "2"

contenu_utf8 = "nom = 'café'\n".encode("utf-8")
source_correcte = b"# coding: utf-8\n" + contenu_utf8
source_incorrecte = b"# coding: latin-1\n" + contenu_utf8
espace_correct, espace_incorrect = {}, {}
exec(compile(source_correcte, "correct.py", "exec"), espace_correct)
exec(compile(source_incorrecte, "incorrect.py", "exec"), espace_incorrect)
assert espace_correct["nom"] == "café"
assert espace_incorrect["nom"] != "café"

import csv

with TemporaryDirectory() as dossier_donnees:
    fichier_csv = Path(dossier_donnees) / "stations.csv"
    fichier_csv.write_bytes("station;volume\nété;3\n".encode("latin-1"))
    with fichier_csv.open("r", encoding="latin-1", newline="") as flux:
        lignes = list(csv.DictReader(flux, delimiter=";"))
    assert lignes == [{"station": "été", "volume": "3"}]
    try:
        fichier_csv.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        pass
    else:
        raise AssertionError("Ces octets Latin-1 ne sont pas du texte UTF-8 valide")

source_avec_shebang = (
    "#!/usr/bin/env python3\n# coding: latin-1\nstatut = 'été'\n"
).encode("latin-1")
variables_source = {}
exec(compile(source_avec_shebang, "controle_lot.py", "exec"), variables_source)
assert variables_source["statut"] == "été"

source_declaration_tardive = (
    "compteur = 1\n# coding: latin-1\nstatut = 'été'\n"
).encode("latin-1")
try:
    compile(source_declaration_tardive, "controle_lot.py", "exec")
except SyntaxError:
    pass  # La première ligne contient du code : la déclaration est ignorée.
else:
    raise AssertionError("Le source Latin-1 sans déclaration reconnue doit échouer")

source_ligne_vide = b"\n# coding: latin-1\nstation = 'caf\xe9'\n"
espace_ligne_vide = {}
exec(compile(source_ligne_vide, "<source-exemple>", "exec"), espace_ligne_vide)
assert espace_ligne_vide["station"] == "café"
