#!/usr/bin/env python3
"""Offline synthetic SaaS feature-packaging ledger; Python 3.9 standard library only."""
from datetime import datetime, timezone
from urllib.parse import urlsplit

REQUIRED = {
    "vendor", "plan", "feature", "market", "audience", "billing_context",
    "source_type", "source_url", "quote_locator", "observed_at", "effective_at",
    "packaging", "feature_terms", "evidence_text",
}
PACKAGING = {"INCLUDED", "ADD_ON", "NOT_INCLUDED", "UNKNOWN"}
SOURCE_TYPES = {"OFFICIAL_PLAN_PAGE", "OFFICIAL_CHANGELOG", "LICENSED_FEED", "MANUAL_APPROVED_REVIEW"}


def parse_utc(value):
    parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if parsed.tzinfo is None:
        raise ValueError("timestamp must include an offset")
    return parsed.astimezone(timezone.utc)


def valid_record(record):
    if not isinstance(record, dict) or set(record) != REQUIRED:
        return False
    if not all(isinstance(record[key], str) and record[key].strip()
               and record[key].strip().upper() not in {"UNKNOWN", "N/A", "TBD"}
               for key in REQUIRED - {"feature_terms", "packaging"}):
        return False
    if not isinstance(record["packaging"], str) or record["packaging"] not in PACKAGING or record["source_type"] not in SOURCE_TYPES:
        return False
    terms = record["feature_terms"]
    if not isinstance(terms, dict) or set(terms) != {"format", "schedule", "monthly_limit", "eligibility"}:
        return False
    if any(not isinstance(terms[k], str) for k in ["format", "schedule", "eligibility"]):
        return False
    if terms["format"] != "CSV" or terms["schedule"] not in {"daily_schedule", "weekly_schedule"}:
        return False
    if type(terms["monthly_limit"]) is not int or terms["monthly_limit"] < 1:
        return False
    if terms["eligibility"] not in {"new_growth_buyers", "all_growth_buyers"}:
        return False
    try:
        source = urlsplit(record["source_url"])
        if source.scheme not in {"https", "http"} or not source.hostname or source.username or source.password:
            return False
        observed_at = parse_utc(record["observed_at"])
        effective_at = parse_utc(record["effective_at"])
    except (ValueError, OverflowError):
        return False
    return effective_at <= observed_at and record["evidence_text"].strip() != ""


def classify(before, after):
    """Return a ledger action; a public package statement is not customer entitlement proof."""
    if not valid_record(before) or not valid_record(after):
        return "HOLD", "malformed, empty, or incomplete comparison evidence"
    context = ("vendor", "plan", "feature", "market", "audience", "billing_context")
    if any(before[key] != after[key] for key in context):
        return "HOLD", "incomparable plan, feature, market, audience, or billing context"
    if parse_utc(after["observed_at"]) < parse_utc(before["observed_at"]):
        return "HOLD", "after observation precedes before observation"
    if parse_utc(after["effective_at"]) < parse_utc(before["effective_at"]):
        return "HOLD", "after effective date precedes before effective date"
    if "UNKNOWN" in {before["packaging"], after["packaging"]}:
        return "HOLD", "packaging evidence is unknown"
    if parse_utc(after["observed_at"]) == parse_utc(before["observed_at"]):
        return "HOLD", "two distinct observation times are required for this change comparison"
    if before["packaging"] == after["packaging"] and before["feature_terms"] == after["feature_terms"]:
        if parse_utc(before["effective_at"]) != parse_utc(after["effective_at"]):
            return "REVIEW", "effective-time evidence changed; human review is required"
        if before["evidence_text"] == after["evidence_text"]:
            return "NO_CHANGE", "same evidenced packaging and normalized terms"
        return "WORDING_ONLY", "same evidenced packaging and normalized terms; preserve copy change without entitlement claim"
    if before["packaging"] == after["packaging"]:
        return "REVIEW", "same packaging category but normalized feature terms changed"
    return "REVIEW", "evidenced public packaging change; ask named owner to verify customer entitlement"


def fixture():
    base = {
        "vendor": "Northwind Metrics (fictional)", "plan": "Growth",
        "feature": "scheduled CSV export", "market": "US", "audience": "new Growth buyer",
        "billing_context": "monthly base subscription; no contract amendment supplied",
        "source_type": "OFFICIAL_PLAN_PAGE", "source_url": "https://example.invalid/plans",
        "quote_locator": "Growth / exports card",
        "feature_terms": {"format": "CSV", "schedule": "daily_schedule", "monthly_limit": 10, "eligibility": "new_growth_buyers"},
        "observed_at": "2026-11-20T09:00:00Z", "effective_at": "2026-11-01T00:00:00Z",
    }
    before = {**base, "observed_at": "2026-10-20T09:00:00Z", "effective_at": "2026-10-01T00:00:00Z",
              "packaging": "INCLUDED", "evidence_text": "Scheduled CSV export included in Growth; daily scheduling; 10 exports per month for new Growth buyers."}
    add_on = {**base, "packaging": "ADD_ON", "evidence_text": "Scheduled CSV export available as a paid add-on; daily scheduling; 10 exports per month for new Growth buyers."}
    wording = {**base, "effective_at": "2026-10-01T00:00:00Z", "packaging": "INCLUDED", "evidence_text": "Automated CSV export included in Growth; daily scheduling; 10 exports per month for new Growth buyers."}
    changed_limit = {**wording, "feature_terms": {**base["feature_terms"], "monthly_limit": 5}, "evidence_text": "Automated CSV export included in Growth; daily scheduling; 5 exports per month for new Growth buyers."}
    missing_card = {**base, "packaging": "UNKNOWN", "feature_terms": "UNKNOWN",
                    "evidence_text": "Feature card not present in this observed plan-page record."}
    return before, add_on, wording, changed_limit, missing_card


def self_test():
    before, add_on, wording, changed_limit, missing_card = fixture()
    assert classify(before, add_on)[0] == "REVIEW"
    assert classify(before, wording)[0] == "WORDING_ONLY"
    assert classify(before, changed_limit)[0] == "REVIEW"
    assert classify(before, missing_card)[0] == "HOLD"
    assert classify(before, {**add_on, "market": "CA"})[0] == "HOLD"
    assert classify(before, {**before, "observed_at": add_on["observed_at"]})[0] == "NO_CHANGE"
    assert classify(before, {**add_on, "feature_terms": "UNKNOWN"})[0] == "HOLD"


if __name__ == "__main__":
    self_test()
    before, add_on, wording, changed_limit, missing_card = fixture()
    print("offline_synthetic_saas_feature_packaging_ledger")
    print("network_requests=0")
    print("included_to_add_on=" + classify(before, add_on)[0])
    print("same_terms_copy_change=" + classify(before, wording)[0])
    print("same_category_changed_limit=" + classify(before, changed_limit)[0])
    print("unchanged_record=" + classify(before, {**before, "observed_at": add_on["observed_at"]})[0])
    print("missing_feature_card=" + classify(before, missing_card)[0])
    print("mismatched_market=" + classify(before, {**add_on, "market": "CA"})[0])
    print("customer_entitlement=UNKNOWN_PUBLIC_PACKAGING_IS_NOT_ACCOUNT_PROOF")
