#!/usr/bin/env python3
"""Offline SanctionsKit result-handling example. Python 3.9+, no dependencies.

Every fixture is invented, including scores and version labels. No network,
matching engine, API key, real screening, or business approval is involved.
"""

import argparse
from copy import deepcopy
from datetime import datetime
import json
import math
from uuid import UUID


REQUEST = {
    "subject": {"name": "Liora Example", "entityType": "person"},
    "package": "sandbox@1",
    "retention": "standard",
}
EXPECTED_SOURCE = "sandbox-synthetic"
EXAMPLE_TIME = "2026-10-04T12:00:00.000Z"
DISCLAIMER = (
    "Potential matches support analyst review. No match means no match in the "
    "selected sources and dataset, not legal clearance. Scores and evidence "
    "categories support review; they are not probabilities of identity or wrongdoing."
)


def fixture_result(potential_match=False):
    """Build a fresh illustrative result shaped like the documented API data."""
    result = {
        "id": "00000000-0000-4000-8000-000000000001",
        "environment": "sandbox",
        "status": "potential_match" if potential_match else "no_match",
        "createdAt": EXAMPLE_TIME,
        "matches": [],
        "coverage": [{
            "sourceId": EXPECTED_SOURCE,
            "version": "illustrative-source-v1",
            "retrievedAt": EXAMPLE_TIME,
            "fresh": True,
        }],
        "versions": {
            "dataset": "illustrative-dataset-v1",
            "matchingEngine": "illustrative-engine-v1",
            "policy": "illustrative-policy-v1",
            "package": REQUEST["package"],
        },
        "disclaimer": DISCLAIMER,
    }
    if potential_match:
        result["matches"] = [{
            "record": {
                "id": "invented:person-001",
                "sourceId": EXPECTED_SOURCE,
                "authority": "Invented example records",
                "list": "Offline demonstration",
                "sourceUrl": "https://www.sanctionskit.com/guides/ofac-api",
                "entityType": "person",
                "names": [{"value": "Liora Example", "kind": "primary"}],
                "identifiers": [],
                "birthDates": [],
                "addresses": [],
                "nationalities": [],
                "designations": [{
                    "category": "other",
                    "programs": ["Invented demonstration only"],
                    "legalReferences": [],
                }],
                "extensions": {"synthetic": True},
            },
            "score": 91,
            "evidence": [{
                "field": "name",
                "queryValue": "Liora Example",
                "sourceValue": "Liora Example",
                "method": "illustrative_name_comparison",
                "contribution": 91,
                "explanation": "Invented review signal; no matching engine was run.",
            }],
            "conflicts": [],
        }]
    return result


def fixtures():
    """Transport tuples are (HTTP status, raw body, transport error occurred)."""
    no_match = {"data": fixture_result()}
    potential = {"data": fixture_result(True)}
    inconsistent = deepcopy(potential)
    inconsistent["data"]["status"] = "no_match"
    stale = deepcopy(no_match)
    stale["data"]["coverage"][0]["fresh"] = False
    error = {"error": {
        "code": "coverage_unavailable",
        "message": "Illustrative unavailable coverage failure.",
        "requestId": "00000000-0000-4000-8000-000000000002",
    }}
    return {
        "no-match": (201, json.dumps(no_match), False),
        "potential-match": (201, json.dumps(potential), False),
        "inconsistent-result": (201, json.dumps(inconsistent), False),
        "stale-coverage": (201, json.dumps(stale), False),
        "malformed-json": (201, "{", False),
        "http-error": (503, json.dumps(error), False),
        "transport-error": (None, None, True),
    }


def nonempty_string(value):
    return isinstance(value, str) and bool(value.strip())


def utc_timestamp(value):
    if not isinstance(value, str) or not value.endswith("Z"):
        return False
    try:
        datetime.fromisoformat(value[:-1] + "+00:00")
        return True
    except ValueError:
        return False


def valid_uuid(value):
    try:
        return isinstance(value, str) and str(UUID(value)) == value.lower()
    except ValueError:
        return False


def valid_candidate(candidate):
    """Check structure needed by this small example, not the entire API schema."""
    if not isinstance(candidate, dict):
        return False
    record = candidate.get("record")
    if not isinstance(record, dict) or record.get("sourceId") != EXPECTED_SOURCE:
        return False
    if not all(nonempty_string(record.get(k)) for k in (
        "id", "authority", "list", "sourceUrl", "entityType"
    )):
        return False
    if record["entityType"] != REQUEST["subject"]["entityType"]:
        return False
    if not all(isinstance(record.get(k), list) for k in (
        "names", "identifiers", "birthDates", "addresses", "nationalities", "designations"
    )) or not isinstance(record.get("extensions"), dict):
        return False
    if not record["names"] or not all(
        isinstance(name, dict) and nonempty_string(name.get("value"))
        and name.get("kind") in ("primary", "alias") for name in record["names"]
    ):
        return False
    score = candidate.get("score")
    if type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 100:
        return False
    evidence, conflicts = candidate.get("evidence"), candidate.get("conflicts")
    if not isinstance(evidence, list) or not isinstance(conflicts, list):
        return False
    for item in evidence:
        if not isinstance(item, dict) or not all(isinstance(item.get(k), str) for k in (
            "field", "queryValue", "sourceValue", "method", "explanation"
        )):
            return False
        contribution = item.get("contribution")
        if type(contribution) not in (int, float) or not math.isfinite(contribution):
            return False
    return all(isinstance(conflict, str) for conflict in conflicts)


def outcome(state, reason, candidates=0, sources=0):
    # Only fixed labels and counts leave the workflow: never print raw inputs,
    # errors, subject values, evidence, tokens, or received metadata.
    return {
        "workflow_state": state,
        "reason": reason,
        "screening_completed": state != "incomplete",
        "business_disposition": "pending",
        "candidate_count": candidates,
        "source_count": sources,
    }


def route_response(http_status, raw_body, transport_error=False):
    """Route this example's sandbox response without approving a business action.

    This is a bounded teaching example, not a general JSON Schema validator or
    transport client. Do not adapt it by relabeling sandbox data as production.
    """
    if transport_error:
        return outcome("incomplete", "transport_failure")
    if type(http_status) is not int or http_status != 201:
        return outcome("incomplete", "http_failure")
    if not isinstance(raw_body, (str, bytes)):
        return outcome("incomplete", "invalid_response")
    try:
        envelope = json.loads(raw_body)
    except (ValueError, UnicodeError):
        return outcome("incomplete", "invalid_response")
    if not isinstance(envelope, dict) or "error" in envelope:
        return outcome("incomplete", "invalid_response")
    result = envelope.get("data")
    if not isinstance(result, dict):
        return outcome("incomplete", "invalid_response")
    if not valid_uuid(result.get("id")) or not utc_timestamp(result.get("createdAt")):
        return outcome("incomplete", "invalid_response")
    if not nonempty_string(result.get("disclaimer")):
        return outcome("incomplete", "invalid_response")
    versions = result.get("versions")
    if not isinstance(versions, dict) or not all(nonempty_string(versions.get(k)) for k in (
        "dataset", "matchingEngine", "policy"
    )):
        return outcome("incomplete", "invalid_response")
    if result.get("environment") != "sandbox" or versions.get("package") != REQUEST["package"]:
        return outcome("incomplete", "coverage_mismatch")
    coverage = result.get("coverage")
    if not isinstance(coverage, list) or len(coverage) != 1:
        return outcome("incomplete", "coverage_mismatch")
    source = coverage[0]
    if not isinstance(source, dict) or source.get("sourceId") != EXPECTED_SOURCE:
        return outcome("incomplete", "coverage_mismatch")
    if not nonempty_string(source.get("version")) or not utc_timestamp(source.get("retrievedAt")):
        return outcome("incomplete", "invalid_response")
    if source.get("fresh") is not True:
        return outcome("incomplete", "coverage_not_fresh")
    matches = result.get("matches")
    if not isinstance(matches, list) or not all(valid_candidate(m) for m in matches):
        return outcome("incomplete", "invalid_response")
    if result.get("status") == "no_match" and len(matches) == 0:
        return outcome("no_match", "apply_remaining_policy_requirements", sources=1)
    if result.get("status") == "potential_match" and len(matches) > 0:
        return outcome("review_required", "analyst_review_required", len(matches), 1)
    return outcome("incomplete", "inconsistent_status")


def main():
    scenarios = fixtures()
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scenario", choices=["all"] + list(scenarios), default="all")
    args = parser.parse_args()
    selected = scenarios if args.scenario == "all" else {args.scenario: scenarios[args.scenario]}
    for name, fixture in selected.items():
        print(json.dumps({"scenario": name, "fixture_only": True, **route_response(*fixture)}, sort_keys=True))


if __name__ == "__main__":
    main()
