import csv
import io
import json
from pathlib import Path
from tempfile import TemporaryDirectory

def inspect_csv(text):
    reader = csv.DictReader(io.StringIO(text, newline=""), strict=True)
    if reader.fieldnames != ["id", "quantity"]:
        raise ValueError("Colonnes attendues : id,quantity")
    accepted, rejected, seen = [], [], set()
    for index, row in enumerate(reader):
        identifier = row.get("id")
        raw_quantity = row.get("quantity")
        if None in row or identifier is None or raw_quantity is None:
            reason = "nombre de champs incorrect"
        elif not identifier.strip():
            reason = "identifiant vide"
        elif identifier in seen:
            reason = "identifiant déjà accepté"
        else:
            try:
                quantity = int(raw_quantity)
            except ValueError:
                reason = "quantité non entière"
            else:
                if quantity < 0:
                    reason = "quantité négative"
                else:
                    accepted.append({"id": identifier, "quantity": quantity})
                    seen.add(identifier)
                    continue
        rejected.append({"index": index, "reason": reason})
    return accepted, rejected

accepted, rejected = inspect_csv("id,quantity\nA,4\nB,-1\nA,2\n,0\n")
assert accepted == [{"id": "A", "quantity": 4}]
assert [item["reason"] for item in rejected] == [
    "quantité négative", "identifiant déjà accepté", "identifiant vide"
]

def audit_fichier(source, destination):
    source, destination = Path(source), Path(destination)
    with source.open("r", encoding="utf-8", newline="") as fichier:
        accepted, rejected = inspect_csv(fichier.read())
    rapport = {
        "accepted": accepted,
        "rejected": rejected,
        "total": sum(row["quantity"] for row in accepted),
    }
    # Le mode x refuse une destination existante, y compris le fichier source.
    with destination.open("x", encoding="utf-8") as fichier:
        json.dump(rapport, fichier, ensure_ascii=False, indent=2)
    return rapport

with TemporaryDirectory() as dossier:
    source = Path(dossier) / "entree.csv"
    destination = Path(dossier) / "rapport.json"
    source.write_text("id,quantity\nB,-1\nB,0\nC,4\n", encoding="utf-8")
    rapport = audit_fichier(source, destination)
    assert rapport["total"] == 4
    assert len(rapport["accepted"]) == 2
    assert rapport["rejected"][0]["reason"] == "quantité négative"
    assert json.loads(destination.read_text(encoding="utf-8")) == rapport
    try:
        audit_fichier(source, source)
    except FileExistsError:
        pass
    else:
        raise AssertionError("La source ne doit pas être écrasée")


def masquer_nom(nom, lettres_trouvees):
    """Masquer par des étoiles les lettres encore inconnues."""
    return "".join(lettre if lettre in lettres_trouvees else "*" for lettre in nom)

nom = "source"
lettres_trouvees = ["o", "e"]
assert masquer_nom(nom, lettres_trouvees) == "*o***e"
lettres_trouvees.extend(["s", "u", "r", "c"])
assert masquer_nom(nom, lettres_trouvees) == nom
scores = {}
participant = "Data"
scores.setdefault(participant, 0)
chances_restantes = 3
if masquer_nom(nom, lettres_trouvees) == nom:
    scores[participant] += chances_restantes
assert scores == {"Data": 3}

acceptees, rejetees = inspect_csv('id,quantity\n"A,B",0\nB,texte\nB,2\n')
assert acceptees == [{"id": "A,B", "quantity": 0}, {"id": "B", "quantity": 2}]
assert rejetees == [{"index": 1, "reason": "quantité non entière"}]
try:
    inspect_csv("id,valeur\nA,2\n")
except ValueError:
    pass
else:
    raise AssertionError("Un en-tête incorrect doit être refusé")

def normaliser_participant(texte):
    """Normaliser un nom alphanumérique d'au moins quatre caractères."""
    nom = texte.capitalize()
    if len(nom) < 4 or not nom.isalnum():
        raise ValueError("Participant invalide")
    return nom

def lire_scores(chemin):
    """Lire et valider les scores JSON ; retourner un dictionnaire vide si absent."""
    def verifier_cles(paires):
        resultat = {}
        for nom, score in paires:
            if nom in resultat:
                raise ValueError("Participant dupliqué dans les scores")
            resultat[nom] = score
        return resultat

    try:
        with open(chemin, "r", encoding="utf-8") as flux:
            scores = json.load(flux, object_pairs_hook=verifier_cles)
    except FileNotFoundError:
        return {}
    if not isinstance(scores, dict) or any(
        not isinstance(nom, str) or type(score) is not int or score < 0
        for nom, score in scores.items()
    ):
        raise ValueError("Format de scores invalide")
    normalises = {}
    for nom, score in scores.items():
        nom_normalise = normaliser_participant(nom)
        if nom_normalise in normalises:
            raise ValueError("Participants identiques après normalisation")
        normalises[nom_normalise] = score
    return normalises

assert normaliser_participant("DATA42") == "Data42"
try:
    normaliser_participant("ab!")
except ValueError:
    pass
else:
    raise AssertionError("Un nom invalide doit être rejeté")
with TemporaryDirectory() as repertoire_scores:
    chemin_scores = Path(repertoire_scores) / "scores.json"
    scores_persistes = lire_scores(chemin_scores)
    assert scores_persistes == {}
    participant = normaliser_participant("data")
    scores_persistes[participant] = scores_persistes.get(participant, 0) + 3
    with open(chemin_scores, "x", encoding="utf-8") as flux:
        json.dump(scores_persistes, flux)
    assert lire_scores(chemin_scores) == {"Data": 3}
    chemin_scores.write_text('{"data": 3}', encoding="utf-8")
    assert lire_scores(chemin_scores) == {"Data": 3}
    for contenu_invalide in ("[]", '{"Data": -1}', '{"Data": true}', '{"Data": 3, "Data": 8}', '{"data": 3, "Data": 8}', "{"):
        chemin_scores.write_text(contenu_invalide, encoding="utf-8")
        try:
            lire_scores(chemin_scores)
        except ValueError:
            pass
        else:
            raise AssertionError("Un fichier de scores invalide doit être refusé")

def jouer_nom(nom, propositions, chances=8):
    trouvees = set()
    flux = iter(propositions)
    while masquer_nom(nom, trouvees) != nom and chances > 0:
        try:
            lettre = next(flux)
        except StopIteration:
            break
        lettre = lettre.lower()
        if len(lettre) != 1 or not lettre.isalpha():
            raise ValueError("Une seule lettre est attendue")
        if lettre in trouvees:
            continue
        if lettre in nom:
            trouvees.add(lettre)
        else:
            chances -= 1
    gagne = masquer_nom(nom, trouvees) == nom
    return gagne, chances, chances if gagne else 0

assert jouer_nom("data", ["d", "d", "x", "x", "a", "t"]) == (True, 6, 6)
assert jouer_nom("data", ["x"] * 8 + ["d", "a", "t"]) == (False, 0, 0)
propositions = iter(["d", "a", "t", "x"])
assert jouer_nom("data", propositions) == (True, 8, 8)
assert next(propositions) == "x"
propositions = iter(["x", "d"])
assert jouer_nom("data", propositions, chances=1) == (False, 0, 0)
assert next(propositions) == "d"

with TemporaryDirectory() as dossier_reprise:
    entree = Path(dossier_reprise) / "entree.csv"
    sortie = Path(dossier_reprise) / "rapport.json"
    entree.write_text('id,quantity\n"A,B",0\n', encoding="utf-8")
    sortie.write_text("rapport precedent", encoding="utf-8")
    try:
        audit_fichier(entree, sortie)
    except FileExistsError:
        pass
    else:
        raise AssertionError("Un rapport existant doit être conservé")
    assert sortie.read_text(encoding="utf-8") == "rapport precedent"
    nouvelle_sortie = Path(dossier_reprise) / "rapport-2.json"
    nouveau_rapport = audit_fichier(entree, nouvelle_sortie)
    assert nouveau_rapport["accepted"] == [{"id": "A,B", "quantity": 0}]

assert len("İ") == 1 and len("İ".lower()) == 2
try:
    jouer_nom("data", ["İ"])
except ValueError:
    pass
else:
    raise AssertionError("La saisie normalisée doit rester une seule lettre")

try:
    inspect_csv('id,quantity\n"lot-inacheve,3')
except csv.Error:
    pass
else:
    raise AssertionError("Un champ CSV non refermé doit interrompre l'audit")

noms_origine = ["ALICE", "Alice"]
noms_normalises = [nom.capitalize() for nom in noms_origine]
assert noms_normalises == ["Alice", "Alice"]
participants = {"participant-01": {"nom": noms_origine[0], "score": 3},
                "participant-02": {"nom": noms_origine[1], "score": 5}}
assert len(participants) == 2
assert participants["participant-01"]["score"] == 3
assert participants["participant-02"]["score"] == 5

import random

def choisir_nom_champ(noms, generateur):
    """Choisir un nom dans une collection non vide avec le générateur fourni."""
    if not noms:
        raise ValueError("La liste des noms est vide")
    return generateur.choice(noms)

noms_champs = ["source", "date", "statut"]
assert choisir_nom_champ(noms_champs, random.Random(7)) == choisir_nom_champ(
    noms_champs, random.Random(7)
)
try:
    choisir_nom_champ([], random.Random(7))
except ValueError:
    pass
else:
    raise AssertionError("Une liste vide doit être refusée")

with TemporaryDirectory() as dossier_parties:
    chemin = Path(dossier_parties) / "scores.json"
    for points in (3, 5):
        scores = lire_scores(chemin)
        scores["Data"] = scores.get("Data", 0) + points
        with chemin.open("w", encoding="utf-8") as fichier:
            json.dump(scores, fichier, ensure_ascii=False)
    assert lire_scores(chemin) == {"Data": 8}

def partie_interactive(nom, lire=input, afficher=print, chances=8):
    """Jouer une partie ; renvoyer son résultat ou None si l'entrée se ferme."""
    if not nom or len(nom) > 8 or not nom.isascii() or not nom.isalpha() or nom != nom.lower():
        raise ValueError("Nom ASCII en minuscules de un à huit caractères attendu")
    if type(chances) is not int or chances <= 0:
        raise ValueError("Nombre de chances positif attendu")
    trouvees = set()
    while chances > 0 and masquer_nom(nom, trouvees) != nom:
        afficher(f"Champ : {masquer_nom(nom, trouvees)} ; chances : {chances}")
        try:
            lettre = lire("Une lettre : ").lower()
        except EOFError:
            afficher("Partie interrompue.")
            return None
        if len(lettre) != 1 or not lettre.isascii() or not lettre.isalpha():
            afficher("Saisis une lettre ASCII.")
            continue
        if lettre in trouvees:
            afficher("Lettre déjà trouvée.")
        elif lettre in nom:
            trouvees.add(lettre)
            afficher("Lettre présente.")
        else:
            chances -= 1
            afficher("Lettre absente.")
    gagne = masquer_nom(nom, trouvees) == nom
    afficher(f"Résultat : {'trouvé' if gagne else 'perdu'} ; champ : {nom}")
    return gagne, chances, chances if gagne else 0

# Dans un terminal : resultat = partie_interactive(choisir_nom_champ(noms_champs, random.Random()))
reponses_partie = iter(["12", "D", "d", "x", "x", "a", "t"])
messages_partie = []
assert partie_interactive("data", lambda invite: next(reponses_partie), messages_partie.append) == (True, 6, 6)
assert "Saisis une lettre ASCII." in messages_partie
assert "Lettre déjà trouvée." in messages_partie
assert messages_partie[-1] == "Résultat : trouvé ; champ : data"

def fin_entree_partie(invite):
    raise EOFError

assert partie_interactive("data", fin_entree_partie, lambda message: None) is None

def session_champs(chemin, noms, generateur, lire=input, afficher=print, chances=8):
    """Charger les scores, conduire les parties et enregistrer le résultat final."""
    scores = lire_scores(chemin)
    while True:
        try:
            participant = normaliser_participant(lire("Participant : "))
            break
        except ValueError:
            afficher("Nom de participant invalide.")
        except EOFError:
            return None
    scores.setdefault(participant, 0)
    while True:
        afficher(f"Participant : {participant} ; score actuel : {scores[participant]}")
        nom = choisir_nom_champ(noms, generateur)
        resultat = partie_interactive(nom, lire, afficher, chances=chances)
        if resultat is None:
            break
        gagne, chances_restantes, points = resultat
        scores[participant] += points
        afficher(f"Score : {scores[participant]}")
        while True:
            try:
                reponse = lire("Continuer (o/n) ? ").strip().lower()
            except EOFError:
                reponse = "n"
            if reponse in ("o", "n"):
                break
            afficher("Réponds par o ou n.")
        if reponse == "n":
            break
    with open(chemin, "w", encoding="utf-8") as flux:
        json.dump(scores, flux, ensure_ascii=False)
    afficher(f"Score final : {scores[participant]}")
    return scores[participant]

class ChoixFixe:
    def choice(self, noms):
        return noms[0]

with TemporaryDirectory() as dossier_session:
    fichier_scores = Path(dossier_session) / "scores.json"
    saisies = iter(["a!", "data", "d", "a", "t", "o"] + ["x"] * 8 + ["n"])
    messages_session = []
    score = session_champs(fichier_scores, ["data"], ChoixFixe(),
                           lambda invite: next(saisies), messages_session.append)
    assert score == 8 and lire_scores(fichier_scores) == {"Data": 8}
    assert "Nom de participant invalide." in messages_session
    assert messages_session.count("Score : 8") == 2

    with fichier_scores.open("w", encoding="utf-8") as flux:
        json.dump({"data": 3, "Autre": 5}, flux)
    nouvelle_session = iter(["data", "d", "a", "t", "n"])
    score = session_champs(fichier_scores, ["data"], ChoixFixe(),
                           lambda invite: next(nouvelle_session), lambda message: None)
    assert score == 11
    assert lire_scores(fichier_scores) == {"Data": 11, "Autre": 5}

with TemporaryDirectory() as dossier_sessions:
    scores_path = Path(dossier_sessions) / "scores.json"
    scores_path.write_text('{"Data": 3, "Nora": 5}', encoding="utf-8")
    premiere_session = iter(["data", "d", "a", "t", "n"])
    assert session_champs(scores_path, ["data"], ChoixFixe(),
                          lambda invite: next(premiere_session), lambda message: None) == 11
    deuxieme_session = iter(["data", "x", "d", "a", "t", "n"])
    assert session_champs(scores_path, ["data"], ChoixFixe(),
                          lambda invite: next(deuxieme_session), lambda message: None) == 18
    assert lire_scores(scores_path) == {"Data": 18, "Nora": 5}
