"""
shipping_service.py — home delivery of the orders placed AFTER a school's deadline (client 2026-11-23).

At the deadline every order is delivered to the school in one go. A family that orders later would cost a trip of its
own, so a school may offer delivery to a French address for a fixed fee per order (`home_delivery`,
`home_delivery_fee`). Switched off, nothing changes: the portal closes at the deadline as it always did.

Rules:
  * The fee is charged only when the order holds something physical: a digital-only order has nothing to send.
  * `orders.total` stays what Stripe charges (products + fee), so the webhook's amount check needs no exception. The fee
    is not a sale of the school: `goods_total` is the base of every sales figure and of the school's share.
  * This is the ONE place where a personal name may be stored (project rule n°1 has this exception, agreed 2026-11-23):
    the ADULT who receives the parcel, never the child. It is never returned to the family portal, which anyone holding
    the code can open, and it is erased by `purge_addresses` once it has served.
"""
import json
import logging
import re
from datetime import timedelta
from typing import Optional

from core.db import get_db
from core.timeutil import utcnow
from services import audit_service

log = logging.getLogger("meeconic.shipping")

# Metropolitan France (with Corsica, 20xxx) and the overseas departments (971-976). Monaco (980xx) is another country
# even though La Poste numbers it like a French department.
_POSTCODE_RE = re.compile(r"^(?:(?:0[1-9]|[1-8]\d|9[0-5])\d{3}|97[1-6]\d{2})$")
# An address that outlives its order for this long is erased even if nobody ever marked the order delivered.
MAX_KEEP_DAYS = 90


def _clean(value: Optional[str]) -> str:
    return " ".join((value or "").split())


def normalize(raw: dict) -> dict:
    """The address as it is stored. Raises ValueError with the message shown to the family."""
    out = {k: _clean(raw.get(k)) for k in ("name", "address", "address2", "postcode", "city")}
    if len(out["name"]) < 2:
        raise ValueError("Nom du destinataire requis pour la livraison.")
    if len(out["address"]) < 3:
        raise ValueError("Adresse de livraison requise.")
    if not _POSTCODE_RE.match(out["postcode"]):
        raise ValueError("Livraison en France uniquement : code postal invalide.")
    if len(out["city"]) < 2:
        raise ValueError("Ville de livraison requise.")
    return {**out, "country": "FR"}


def ships_home(row) -> bool:
    """Delivered to a home, so it must stay out of what is handed to the school (labels, delivery slip)."""
    return bool(row.get("home_delivery"))


def fee_of(row) -> float:
    return float(row.get("shipping_fee") or 0)


def goods_total(row) -> float:
    """What the products of the order add up to: the base of the sales figures, without the delivery fee."""
    return round(float(row["total"]) - fee_of(row), 2)


def address_of(row) -> Optional[dict]:
    """The stored address, or None (not a home delivery, or already erased). Older rows hold free text: not ours."""
    if not ships_home(row) or not row.get("shipping_address"):
        return None
    try:
        data = json.loads(row["shipping_address"])
    except ValueError:
        return None
    return data if isinstance(data, dict) else None


def purge_addresses() -> int:
    """Daily (cleanup_service): erases the addresses that have served, at the school's RGPD retention. An order still
    being prepared keeps its address, up to MAX_KEEP_DAYS. The order itself and its fee stay."""
    from services import school_service
    erased = 0
    now = utcnow()
    for school in school_service.list_schools():
        sid = school["id"]
        days = int(school_service.get_settings(sid).get("rgpd_days") or 30)
        cutoff = (now - timedelta(days=days)).isoformat()
        hard = (now - timedelta(days=max(days, MAX_KEEP_DAYS))).isoformat()
        with get_db() as conn:
            n = conn.execute(
                "UPDATE orders SET shipping_address=NULL WHERE school_id=? AND home_delivery=1 "
                "AND shipping_address IS NOT NULL AND created_at < ? "
                "AND (batch_status IN ('delivered','cancelled') OR payment_status != 'paid' OR created_at < ?)",
                (sid, cutoff, hard)).rowcount
            conn.commit()
        if n:
            erased += n
            audit_service.log_event("order.address_rgpd_delete", resource_type="school", resource_id=sid, school_id=sid,
                                    details={"addresses": n, "retention_days": days}, severity="critical")
    if erased:
        log.info("GDPR: %d delivery address(es) erased", erased)
    return erased
