#!/usr/bin/env python3
"""Offline, synthetic tender-review ledger. It makes no network or file calls."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Dict, Iterable, List, Optional, Tuple


UTC = timezone.utc
AS_OF = datetime(2026, 12, 1, 12, 0, tzinfo=UTC)
PREPARATION_BUFFER = timedelta(hours=36)


@dataclass(frozen=True)
class Notice:
    source: str
    procedure: str
    lot: str
    revision: int
    kind: str
    state: str
    scope: str
    deadline: Optional[str]
    normalized_zone: Optional[str]
    eligibility: str

    @property
    def identity(self) -> Tuple[str, str, str]:
        return (self.source, self.procedure, self.lot)


def latest_by_identity(rows: Iterable[Notice]) -> List[Notice]:
    latest: Dict[Tuple[str, str, str], Notice] = {}
    seen_revisions = set()
    for row in rows:
        if not all(isinstance(value, str) and value for value in (row.source, row.procedure, row.lot, row.kind, row.state, row.scope, row.eligibility)):
            raise ValueError("invalid synthetic notice field")
        if isinstance(row.revision, bool) or not isinstance(row.revision, int) or row.revision < 1:
            raise ValueError("invalid revision")
        revision_identity = row.identity + (row.revision,)
        if revision_identity in seen_revisions:
            raise ValueError("ambiguous revision identity")
        seen_revisions.add(revision_identity)
        previous = latest.get(row.identity)
        if previous is None or row.revision > previous.revision:
            latest[row.identity] = row
    return [latest[key] for key in sorted(latest)]


def parse_utc(value: str, normalized_zone: str) -> datetime:
    """This synthetic contract accepts an explicit offset and normalizes to UTC."""
    if normalized_zone != "UTC" or not isinstance(value, str):
        raise ValueError("missing normalized UTC deadline")
    normalized = value.replace("Z", "+00:00")
    parsed = datetime.fromisoformat(normalized)
    if parsed.tzinfo is None or parsed.utcoffset() is None:
        raise ValueError("deadline needs an explicit offset")
    return parsed.astimezone(UTC)


def decision(row: Notice) -> str:
    if row.state == "cancelled":
        return "EXCLUDED_CANCELLED"
    if row.kind == "award":
        return "RESEARCH_ONLY_AWARD"
    if row.kind == "sources-sought":
        return "RESEARCH_ONLY_SOURCE_SOUGHT"
    if row.kind != "solicitation" or row.state != "active":
        return "HOLD_UNKNOWN_NOTICE_KIND_OR_STATE"
    if row.scope != "data-platform":
        return "EXCLUDED_SCOPE_MISMATCH"
    if row.deadline is None or row.normalized_zone is None:
        return "HOLD_UNKNOWN_TIMEZONE_OR_DEADLINE"
    if row.eligibility != "confirmed-for-review":
        return "HOLD_UNKNOWN_ELIGIBILITY"
    try:
        deadline = parse_utc(row.deadline, row.normalized_zone)
    except ValueError:
        return "HOLD_UNKNOWN_TIMEZONE_OR_DEADLINE"
    if deadline <= AS_OF:
        return "EXCLUDED_EXPIRED"
    if deadline - AS_OF < PREPARATION_BUFFER:
        return "HOLD_PREPARATION_WINDOW"
    return "HUMAN_REVIEW_CANDIDATE"


def ledger() -> list[Notice]:
    return [
        Notice("SAM", "SAM-101", "LOT-1", 1, "solicitation", "active", "data-platform", "2026-12-05T18:00:00Z", "UTC", "confirmed-for-review"),
        Notice("SAM", "SAM-101", "LOT-1", 2, "solicitation", "active", "data-platform", "2026-12-02T18:00:00Z", "UTC", "confirmed-for-review"),
        Notice("SAM", "SAM-202", "LOT-1", 1, "award", "active", "data-platform", None, None, "confirmed-for-review"),
        Notice("TED", "TED-303", "LOT-A", 1, "sources-sought", "active", "data-platform", None, None, "confirmed-for-review"),
        Notice("TED", "TED-404", "LOT-A", 1, "solicitation", "active", "data-platform", "2026-12-08T09:00:00", None, "confirmed-for-review"),
        Notice("SAM", "SAM-505", "LOT-1", 1, "solicitation", "cancelled", "data-platform", "2026-12-09T16:00:00Z", "UTC", "confirmed-for-review"),
        Notice("TED", "TED-606", "LOT-B", 1, "solicitation", "active", "construction", "2026-12-10T16:00:00Z", "UTC", "confirmed-for-review"),
        Notice("TED", "TED-707", "LOT-C", 1, "solicitation", "active", "data-platform", "2026-12-11T16:00:00Z", "UTC", "unknown"),
        Notice("SAM", "SAM-808", "LOT-1", 1, "solicitation", "active", "data-platform", "2026-12-12T16:00:00Z", "UTC", "confirmed-for-review"),
        Notice("TED", "TED-909", "LOT-D", 1, "solicitation", "active", "data-platform", "2026-12-01T11:00:00Z", "UTC", "confirmed-for-review"),
    ]


def self_test() -> None:
    rows = ledger()
    latest = latest_by_identity(rows)
    assert len(rows) == 10 and len(latest) == 9
    assert decision(next(row for row in latest if row.procedure == "SAM-101")) == "HOLD_PREPARATION_WINDOW"
    assert decision(next(row for row in latest if row.procedure == "SAM-808")) == "HUMAN_REVIEW_CANDIDATE"
    assert parse_utc("2026-12-12T16:00:00+00:00", "UTC") == parse_utc("2026-12-12T08:00:00-08:00", "UTC")
    assert decision(Notice("X", "expired", "1", 1, "solicitation", "active", "data-platform", "2026-12-01T11:00:00Z", "UTC", "confirmed-for-review")) == "EXCLUDED_EXPIRED"
    assert decision(Notice("X", "unknown", "1", 1, "other", "active", "data-platform", "2026-12-12T16:00:00Z", "UTC", "confirmed-for-review")) == "HOLD_UNKNOWN_NOTICE_KIND_OR_STATE"
    try:
        latest_by_identity([rows[0], Notice("SAM", "SAM-101", "LOT-1", 1, "solicitation", "active", "data-platform", None, None, "unknown")])
    except ValueError:
        pass
    else:
        raise AssertionError("same revision must hold")


def main() -> None:
    self_test()
    rows = ledger()
    latest = latest_by_identity(rows)
    print("offline_synthetic_tender_opportunity_review")
    print("network_requests=0 files_read=0 dependencies=standard_library")
    print("as_of=2026-12-01T12:00:00Z preparation_buffer_hours=36")
    print(f"raw_rows={len(rows)} latest_procedure_lot_states={len(latest)}")
    for row in rows:
        later = [candidate.revision for candidate in latest if candidate.identity == row.identity and candidate.revision > row.revision]
        if later:
            print(f"{row.source}/{row.procedure}/{row.lot} revision={row.revision} superseded_by={max(later)}")
    for row in latest:
        print(f"{row.source}/{row.procedure}/{row.lot} revision={row.revision} decision={decision(row)}")
    print(f"accounting={len(rows)}/{len(rows)} raw rows retained; {len(latest)}/{len(latest)} latest procedure-lot states decided")
    print("PASS: candidate is a human review gate, not eligibility, a bid instruction, lead, win, or revenue claim", end="")


if __name__ == "__main__":
    main()
