"""Audit 2026-10-30: what used to fail in silence now reaches the team (or is retried)."""
import asyncio
import time
import uuid
from datetime import timedelta

import pytest

from conftest import DEMO_CODE, SCHOOL, insert_order, item
from core import config
from core.db import get_db
from core.timeutil import utcnow
from services import alert_service
from test_payments import _event, _new_order, _order


@pytest.fixture
def alerts(monkeypatch):
    sent = []
    monkeypatch.setattr(alert_service, "notify", lambda key, subject, body="": sent.append(key))
    return sent


async def test_a_mail_that_fails_or_cannot_be_sent_alerts(monkeypatch, alerts):
    from services import email_service

    async def boom(*a, **kw):
        raise OSError("smtp down")
    monkeypatch.setattr(email_service, "is_configured", lambda: True)
    monkeypatch.setattr(email_service.aiosmtplib, "send", boom)
    assert await email_service._send("a@x.fr", "Sujet", "<p>x</p>") is False
    monkeypatch.setattr(email_service, "is_configured", lambda: False)
    assert await email_service._send("a@x.fr", "Sujet", "<p>x</p>") is False
    assert alerts == ["email-failed", "email-not-configured"]


def test_an_alert_that_could_not_be_sent_frees_its_cooldown(monkeypatch):
    monkeypatch.setenv("SMTP_USER", "u")
    monkeypatch.setenv("SMTP_PASSWORD", "p")
    monkeypatch.setattr(config, "ALERT_EMAIL", "ops@example.com")

    def boom(*a, **kw):
        raise OSError("smtp down")
    monkeypatch.setattr(alert_service.smtplib, "SMTP", boom)
    key = f"free-{uuid.uuid4().hex[:6]}"
    assert alert_service._cooldown_ok(key) is True
    assert alert_service._cooldown_ok(key) is False             # inside the cooldown
    alert_service._smtp_send("s", "b", key)                      # fails: nothing delivered
    assert alert_service._cooldown_ok(key) is True               # so the next occurrence may try again


async def test_unknown_payment_dispute_and_refund_of_an_unpaid_order_alert(client, alerts):
    await client.post("/api/stripe/webhook", json=_event("payment_intent.succeeded", "pi_inconnu_zz", 100))
    await client.post("/api/stripe/webhook", json={"type": "charge.dispute.created", "data": {"object": {
        "id": "dp_1", "charge": "ch_1", "amount": 900, "reason": "fraudulent"}}})
    oid, pi = _new_order()                                       # unpaid
    await client.post("/api/stripe/webhook", json={"type": "charge.refunded", "data": {"object": {
        "id": "ch_2", "payment_intent": pi, "amount": 900, "amount_refunded": 900}}})
    assert alerts == ["stripe-unknown-pi:pi_inconnu_zz", "stripe-dispute:dp_1", f"stripe-refund-unpaid:{oid}"]


async def test_a_storage_hiccup_after_payment_still_sends_the_confirmation(client, monkeypatch, alerts):
    """The order is booked paid before the originals are read: a Stripe retry would then see it paid and stop, so the
    confirmation must go out WITHOUT attachments instead of never."""
    import main
    from services import email_service
    oid, pi = _new_order(items=[item(fmt="digital", label="HD") | {"digital": True, "physical": False}])
    sent = []

    async def fake_confirmation(**kw):
        sent.append(kw["attachments"])
        return True

    async def fake_company(**kw):
        return True
    monkeypatch.setattr(main, "EMAIL_ENABLED", True)
    monkeypatch.setattr(email_service, "send_order_confirmation", fake_confirmation)
    monkeypatch.setattr(email_service, "send_company_notification", fake_company)

    def boom(row, items):
        raise OSError("bucket down")
    monkeypatch.setattr(main, "_prepare_confirmation", boom)
    r = await client.post("/api/stripe/webhook", json=_event("payment_intent.succeeded", pi, 900))
    assert r.status_code == 200
    await asyncio.sleep(0.1)
    assert (await _order(client, oid))["payment_status"] == "paid"
    assert sent == [[]]
    assert alerts == [f"order-email-prep:{oid}"]


async def test_a_paid_order_whose_webhook_never_came_is_booked_within_minutes(client, monkeypatch):
    import stripe
    from services import cleanup_service, payment_keys_service
    oid, pi = _new_order(created_at=(utcnow() - timedelta(minutes=30)).isoformat())
    fresh, pi_fresh = _new_order()                               # created now: too young to be suspect
    asked = []

    def retrieve(pi_id, **kw):
        asked.append(pi_id)
        return {"status": "succeeded", "amount": 900, "amount_received": 900}
    monkeypatch.setattr(payment_keys_service, "stripe_secret", lambda: "sk_test_x")
    monkeypatch.setattr(stripe.PaymentIntent, "retrieve", staticmethod(retrieve))
    assert cleanup_service.check_recent_unpaid() == 1
    assert asked == [pi]
    assert await cleanup_service.book_orders_paid_at_stripe() == 1
    assert (await _order(client, oid))["payment_status"] == "paid"
    assert (await _order(client, fresh))["payment_status"] == "unpaid"


async def test_a_booking_that_fails_alerts_the_team(monkeypatch, alerts):
    from services import cleanup_service

    async def boom(pi, amount):
        raise RuntimeError("db gone")
    monkeypatch.setattr(cleanup_service, "_payment_reconciler", boom)
    cleanup_service._paid_at_stripe.append(("pi_x1", 900))
    assert await cleanup_service.book_orders_paid_at_stripe() == 0
    assert "stripe-reconcile-failed:pi_x1" in alerts


def test_unreadable_retention_never_deletes_on_the_env_default(monkeypatch):
    from services import cleanup_service, school_service

    def boom(sid):
        raise RuntimeError("db hiccup")
    monkeypatch.setattr(school_service, "get_settings", boom)
    assert cleanup_service._retention_days(school_id=SCHOOL) == config.PHOTO_RETENTION_DAYS      # old behaviour
    with pytest.raises(RuntimeError):
        cleanup_service._retention_days(school_id=SCHOOL, strict=True)                           # deletion path


def test_mail_misconfiguration_is_reported(monkeypatch):
    from core import security
    from services import email_service
    monkeypatch.delenv("EMAIL_ENABLED", raising=False)
    monkeypatch.setattr(email_service, "is_configured", lambda: False)
    monkeypatch.setattr(alert_service, "recipients", lambda: "")
    assert len(security.mail_config_warnings()) == 3
    monkeypatch.setenv("EMAIL_ENABLED", "true")
    monkeypatch.setattr(email_service, "is_configured", lambda: True)
    monkeypatch.setattr(alert_service, "recipients", lambda: "ops@example.com")
    assert security.mail_config_warnings() == []


def test_a_stalled_cleanup_is_flagged_by_the_monitor(monkeypatch, alerts):
    from services import monitor_service
    with get_db() as conn:
        conn.execute("INSERT OR REPLACE INTO app_kv (key, value) VALUES ('heartbeat:cleanup', ?)",
                     (str(time.time() - 40 * 3600),))
        conn.commit()
    try:
        monitor_service.check_once()
        assert "cleanup-stale" in alerts
    finally:
        with get_db() as conn:
            conn.execute("DELETE FROM app_kv WHERE key='heartbeat:cleanup'")
            conn.commit()


async def test_the_printed_mail_is_rearmed_when_it_did_not_leave(monkeypatch):
    import admin
    from services import email_service
    oid, _ = _new_order(payment_status="paid")
    with get_db() as conn:
        conn.execute("UPDATE orders SET printed_notified_at=? WHERE id=?", ("2026-10-30T10:00:00", oid))
        conn.commit()

    async def failing(*a, **kw):
        return False
    monkeypatch.setattr(email_service, "send_order_printed", failing)
    await admin._send_printed_or_rearm("a@x.fr", oid, DEMO_CODE, [], "fr")
    with get_db() as conn:
        assert conn.execute("SELECT printed_notified_at FROM orders WHERE id=?", (oid,)).fetchone()["printed_notified_at"] is None


async def test_the_family_list_never_shows_the_whole_address(client):
    oid, _ = _new_order(payment_status="paid")
    assert (await _order(client, oid))["customer_email"] == "cl***@example.com"


async def test_a_payment_of_another_app_on_the_shared_stripe_account_is_ignored_without_alert(client, alerts):
    ev = _event("payment_intent.succeeded", "pi_zoo", 700)
    ev["data"]["object"]["metadata"] = {"orderId": "cmw6fxbmo00t"}
    r = await client.post("/api/stripe/webhook", json=ev)
    assert r.status_code == 200 and alerts == []
