"""Exercice local fictif : aucune connexion à Business Central.

Ces champs représentent le registre interne, pas une réponse API brute.
Les seuils sont des choix pédagogiques, pas des exigences Microsoft.
L'identité inclut le contexte pour éviter les mélanges entre installations.
"""
import json
from datetime import datetime, timedelta, timezone

EXPECTED = ("tenant-demo", "production-demo", "company-A", "salesOrders", "sub-A")
MARGIN = timedelta(hours=24)
MAX_AGE = timedelta(hours=1)


def date(value):
    result = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if result.tzinfo is None:
        raise ValueError("Un fuseau explicite est obligatoire")
    return result.astimezone(timezone.utc)


def classify(observation, now):
    if observation is None or observation.get("identity") != EXPECTED:
        return "verifier"
    observed = date(observation["observed_at"])
    expires = date(observation["expires_at"])
    if observed > now:
        return "verifier"
    if now >= expires:
        return "incident"
    if now - observed > MAX_AGE:
        return "verifier"
    return "renouveler" if expires - now <= MARGIN else "surveiller"


def renewal_after_timeout(previous, current, now):
    """Compare deux lectures du même abonnement après perte de la réponse PATCH."""
    state = classify(current, now)
    if state in {"verifier", "incident"}:
        return state
    if current["notification_url"] != previous["notification_url"]:
        return "verifier"
    if date(current["observed_at"]) <= date(previous["observed_at"]):
        return "verifier"
    if date(current["expires_at"]) > date(previous["expires_at"]):
        return "prolongation_observee"
    return "prolongation_non_confirmee"


def reconcile(source, downstream):
    """Compare les révisions métier dans l'inventaire fictif arrêté à 08 h 00."""
    decisions = {}
    for document, revision in source.items():
        current = downstream.get(document)
        if revision is None or (current is not None and current > revision):
            decisions[document] = "a_investiguer"
        elif current == revision:
            decisions[document] = "deja_rapproche"
        else:
            decisions[document] = "a_rapprocher"
    return decisions


def close_incident(subscription_confirmed, scope_complete, decisions):
    return (
        subscription_confirmed
        and scope_complete
        and all(decision == "deja_rapproche" for decision in decisions.values())
    )


def exercise():
    base = {
        "identity": EXPECTED,
        "observed_at": "2026-10-24T09:00:00Z",
        "expires_at": "2026-10-25T10:00:00Z",
        "notification_url": "https://portail.example/hooks/business-central",
    }
    cases = [
        (base, "2026-10-24T09:00:00Z", "surveiller"),
        (base, "2026-10-24T10:00:00Z", "renouveler"),
        ({**base, "observed_at": "2026-10-25T10:00:00Z"},
         "2026-10-25T10:00:00Z", "incident"),
        (base, "2026-10-24T10:00:01Z", "verifier"),
        ({**base, "identity": (*EXPECTED[:-1], "sub-B")},
         "2026-10-24T09:00:00Z", "verifier"),
        ({**base, "identity": (EXPECTED[0], "sandbox-demo", *EXPECTED[2:])},
         "2026-10-24T09:00:00Z", "verifier"),
        (None, "2026-10-24T09:00:00Z", "verifier"),
        (base, "2026-10-24T08:59:59Z", "verifier"),
    ]
    for number, (observation, instant, expected) in enumerate(cases, 1):
        actual = classify(observation, date(instant))
        assert actual == expected, (number, actual, expected)
    reloaded_at = date("2026-10-24T10:02:00Z")
    reloaded = {**base, "observed_at": "2026-10-24T10:02:00Z"}
    extended = {**reloaded, "expires_at": "2026-10-27T10:01:00Z"}
    assert renewal_after_timeout(base, extended, reloaded_at) == "prolongation_observee"
    assert renewal_after_timeout(base, reloaded, reloaded_at) == "prolongation_non_confirmee"
    assert renewal_after_timeout(base, None, reloaded_at) == "verifier"
    assert renewal_after_timeout(base, base, reloaded_at) == "verifier"
    wrong_receiver = {**extended, "notification_url": "https://other.example/hooks"}
    assert renewal_after_timeout(base, wrong_receiver, reloaded_at) == "verifier"
    wrong_company = {**extended, "identity": (*EXPECTED[:2], "company-B", *EXPECTED[3:])}
    assert renewal_after_timeout(base, wrong_company, reloaded_at) == "verifier"
    exact_expiry = date(base["expires_at"])
    assert renewal_after_timeout(base, reloaded, exact_expiry) == "incident"

    source = {"C-741": 3, "C-742": 5, "C-743": None}
    downstream = {"C-741": 2, "C-742": 5, "C-743": 1}
    decisions = reconcile(source, downstream)
    assert decisions == {
        "C-741": "a_rapprocher", "C-742": "deja_rapproche", "C-743": "a_investiguer",
    }
    assert reconcile({"C-741": 3}, {"C-741": 4}) == {"C-741": "a_investiguer"}
    assert reconcile({"C-741": 3}, {}) == {"C-741": "a_rapprocher"}
    downstream["C-741"] = 3
    after_replay = reconcile(source, downstream)
    assert after_replay["C-741"] == "deja_rapproche"
    assert after_replay["C-742"] == "deja_rapproche"
    assert after_replay["C-743"] == "a_investiguer"
    assert not close_incident(True, True, after_replay)
    assert not close_incident(True, False, {})
    assert not close_incident(False, True, {"C-741": "deja_rapproche"})
    assert close_incident(True, True, {"C-741": "deja_rapproche", "C-742": "deja_rapproche"})

    cutoff = date("2026-10-26T08:00:00Z")
    last_proven = date("2026-10-25T09:40:00Z")
    assert cutoff - exact_expiry == timedelta(hours=22)
    assert cutoff - last_proven == timedelta(hours=22, minutes=20)
    try:
        date("2026-10-25T10:00:00")
    except ValueError:
        pass
    else:
        raise AssertionError("Une heure sans fuseau a été acceptée")

    print(json.dumps({
        "checks": len(cases) + 20,
        "first_reconciliation": decisions,
        "after_replay": after_replay,
        "renewal_after_timeout": renewal_after_timeout(base, extended, reloaded_at),
        "downtime_hours": 22,
        "reconciliation_minutes": 22 * 60 + 20,
        "closed_after_replay": close_incident(True, True, after_replay),
    }))


if __name__ == "__main__":
    exercise()
