"""Read-only chronological numbers for the completed 2026 archive repair. Database numbers remain immutable publication identities. These helpers belong at the public presentation/routing boundary, never in packets, review receipts or editorial-memory hashes. The permutation activates only for the complete, exact set of original published editions; corrections do not redefine it. """ from __future__ import annotations import copy import json import re from datetime import date, timedelta from typing import Any from sqlalchemy import select from sqlalchemy.orm import Session, object_session from .models import Edition CHRONOLOGICAL_LINK_SCHEME = "chronological-v1" # stored number, public number, original packet hash, reporting week start _ARCHIVE_IDENTITIES = ( (8, 7, "a3b639ab7e93f5745d18fb67f922b6e8fc93ee67b19b2c4d9bd1410264272965", date(2026, 9, 7)), (9, 8, "f57c1a68e1331d500912bcb12367ba48900567476d49990b1aef884e911334b1", date(2026, 9, 14)), (10, 9, "9e1843cd27c92b7d6bca5278a91e05bcb370a349387a927b9d81d288b26898cc", date(2026, 9, 21)), (11, 10, "c1bbe6977f741acc191a1ea5a44b7810e3a16e716109474ddcd1bcd3f7c3a35e", date(2026, 9, 28)), (12, 11, "8a041df2c49bb52c6c7e5a282ad2400fda04362ade31ad01421c346855d447a7", date(2026, 10, 5)), (7, 12, "8a243820a28305527b8b8c1cfecde54e2b31fc38369fe1fd64b0fb325eb259b3", date(2026, 10, 12)), ) _INTERNAL_ISSUE_URL = re.compile( r"(?P(?:https://ledecaf\.com)?/(?:fr/numeros|en/issues|api/v2/issues)/)" r"(?P[0-9]+)(?P(?:[/#?][^\s]*)?)\Z" ) def session_mapping(session: Session | None) -> dict[int, int]: """Return the six stored-to-public changes, or an empty native mapping. Read original Edition columns, not the newest correction or localized snapshot. No autoflush, database mutation or cache is introduced. A partial historical projection and an unrelated database therefore retain their native numbering, including when reused within the same Session. """ if session is None: return {} numbers = [item[0] for item in _ARCHIVE_IDENTITIES] with session.no_autoflush: rows = session.execute( select( Edition.number, Edition.status, Edition.week_start, Edition.week_end, Edition.payload_json, ).where(Edition.number.in_(numbers)) ).all() if len(rows) != len(_ARCHIVE_IDENTITIES): return {} by_number = {row.number: row for row in rows} for stored, _public, digest, start in _ARCHIVE_IDENTITIES: row = by_number.get(stored) if (row is None or row.status != "published" or row.week_start != start or row.week_end != start + timedelta(days=6)): return {} try: payload = json.loads(row.payload_json) except (TypeError, ValueError): return {} build = payload.get("build") if isinstance(payload, dict) else None if not isinstance(build, dict) or build.get("packet_sha256") != digest: return {} return {stored: public for stored, public, _digest, _start in _ARCHIVE_IDENTITIES} def public_number(edition: Edition, session: Session | None = None) -> int: """Project an original Edition's stored number for a public reader. An attached edition supplies its Session when one is not explicitly passed. A detached edition without a Session cannot establish the complete archive, so its stored number is returned unchanged. Corrections use their parent Edition, never an EditionRevision as this argument. """ active_session = session if session is not None else object_session(edition) if active_session is None: return edition.number with active_session.no_autoflush: # Even reading an expired ORM attribute can otherwise trigger autoflush. number = edition.number return session_mapping(active_session).get(number, number) def stored_number(session: Session | None, number: int) -> int: """Resolve a public route number to the immutable stored number. Zero, earlier editions and future numbers outside this permutation remain unchanged. This does not create legacy aliases for the reassigned URLs. """ inverse = {public: stored for stored, public in session_mapping(session).items()} return inverse.get(number, number) def rewrite_internal_links(data: Any, session: Session | None) -> Any: """Deep-copy a stored public projection and rewrite whole issue URL values. Only /fr/numeros/N, /en/issues/N, /api/v2/issues/N and exact https://ledecaf.com equivalents qualify. Path suffixes, query strings and fragments survive byte-for-byte; external URLs, dictionary keys and URLs embedded in prose/Markdown citations are not rewritten. Each value is mapped once, not repeatedly through the permutation. Call once at the stored-to-public boundary: already projected URLs cannot be distinguished from stored URLs and must not be passed again. """ mapping = session_mapping(session) def rewrite(value: Any) -> Any: if isinstance(value, str): match = _INTERNAL_ISSUE_URL.fullmatch(value) if match: digits = match["number"].lstrip("0") or "0" if len(digits) > 2: return value number = int(digits) if number in mapping: return match["prefix"] + str(mapping[number]) + match["suffix"] return value if isinstance(value, dict): return {key: rewrite(item) for key, item in value.items()} if isinstance(value, list): return [rewrite(item) for item in value] if isinstance(value, tuple): return tuple(rewrite(item) for item in value) return value return rewrite(copy.deepcopy(data)) def project_dossier(data: Any, session: Session | None) -> Any: """Project a validated public dossier after its translation hash was checked. The underlying inquiry/archive records retain storage identities for exact evidence and translation bindings. Use this once at the HTTP boundary. Generated chapter numbers/links and the latest published story's review date are projected; authored evidence URLs and prose retain their own addresses. """ mapping = session_mapping(session) projected = copy.deepcopy(data) projected_chapters = set() def chapter(value: Any) -> None: if not isinstance(value, dict) or type(value.get("issue_number")) is not int: return if id(value) in projected_chapters: return projected_chapters.add(id(value)) stored = value["issue_number"] public = mapping.get(stored, stored) url = value.get("story_url") match = _INTERNAL_ISSUE_URL.fullmatch(url) if isinstance(url, str) else None # Only this derived chapter link is known to use storage numbering. # Evidence URLs and other authored text may already use public numbers. if match and (match["number"].lstrip("0") or "0") == str(stored): value["story_url"] = match["prefix"] + str(public) + match["suffix"] value["issue_number"] = public def dossier(value: Any) -> None: if isinstance(value, list): for item in value: dossier(item) elif isinstance(value, dict): from .dossier_reviews import published_review_date # Resolve using storage identities before projecting reader numbers. # Do not include this derived date in legacy translation hashes. value["next_review_at"] = published_review_date(session, value) chapter(value.get("latest_update")) for item in value.get("timeline", []): chapter(item) dossier(projected) return projected