#!/usr/bin/env python3
"""Offline synthetic regional-search evidence worksheet; Python 3.9+ stdlib only.

No network calls, browser automation, Google queries, traffic generation, proxy
use, credentials, or attempts to bypass limits. Inputs describe a proposed
client report; they do not establish a live rank, city-level location, demand,
traffic, sales, or provider capability.
"""
from collections import Counter
from datetime import datetime, timedelta


SOURCE_TYPES = {"OFFICIAL_EXPORT", "LICENSED_EXPORT", "MANUAL_OBSERVATION"}
SOURCE_SEMANTICS = {
    "OFFICIAL_EXPORT": "COUNTRY_AGGREGATE",
    "LICENSED_EXPORT": "LICENSED_SCOPE",
    "MANUAL_OBSERVATION": "MANUAL_CONTEXT",
}
PERMISSIONS = {"PERMITTED", "UNKNOWN", "NOT_PERMITTED"}
CONTEXT_STATES = {"RECORDED", "NOT_APPLICABLE", "MISSING"}
OBSERVATIONS = {"PRESENT", "NOT_PRESENT", "MISSING"}
METRICS = {"GSC_AVERAGE_POSITION", "OBSERVED_RESULT", "NO_METRIC"}


def classify(record):
    """Return the narrow report disposition for one proposed observation."""
    required = {"id", "source_type", "source_semantics", "permission", "country",
                "city", "device", "language", "timezone", "window_start", "window_end",
                "observed_at", "observation", "metric", "metric_value"}
    if set(record) != required:
        raise ValueError("record must have exactly the required fields")
    if record["source_type"] not in SOURCE_TYPES:
        raise ValueError("invalid source_type")
    if record["source_semantics"] != SOURCE_SEMANTICS[record["source_type"]]:
        raise ValueError("source semantics incompatible with source_type")
    if record["permission"] not in PERMISSIONS:
        raise ValueError("invalid permission")
    if record["device"] not in CONTEXT_STATES or record["language"] not in CONTEXT_STATES:
        raise ValueError("invalid context state")
    if record["observation"] not in OBSERVATIONS:
        raise ValueError("invalid observation")
    if record["metric"] not in METRICS:
        raise ValueError("invalid metric")
    if not record["id"] or not record["country"] or len(record["country"]) != 2:
        raise ValueError("id and ISO-like two-letter country are required")
    if record["timezone"] != "UTC":
        raise ValueError("worksheet requires UTC timestamps")
    try:
        start = datetime.fromisoformat(record["window_start"].replace("Z", "+00:00"))
        end = datetime.fromisoformat(record["window_end"].replace("Z", "+00:00"))
        observed = datetime.fromisoformat(record["observed_at"].replace("Z", "+00:00"))
    except (AttributeError, ValueError):
        raise ValueError("timestamps must be ISO-8601")
    if any(value.tzinfo is None or value.utcoffset() != timedelta(0)
           for value in (start, end, observed)):
        raise ValueError("timestamps must be UTC")
    if not start < end:
        raise ValueError("invalid reporting window")
    if end - start > timedelta(days=31) or not start <= observed <= end:
        raise ValueError("reporting window must contain observation and be at most 31 days")
    if record["source_type"] != "MANUAL_OBSERVATION" and record["city"] is not None:
        raise ValueError("only manual observation may state an asserted city")
    if record["source_type"] == "MANUAL_OBSERVATION" and not record["city"]:
        raise ValueError("manual observation requires asserted city context")
    if record["source_type"] == "OFFICIAL_EXPORT" and record["language"] not in {"NOT_APPLICABLE", "MISSING"}:
        raise ValueError("official aggregate language is not a GSC dimension")
    if record["source_type"] == "MANUAL_OBSERVATION" and record["language"] not in {"RECORDED", "MISSING"}:
        raise ValueError("manual observation requires recorded language context")
    if record["metric"] == "OBSERVED_RESULT" and record["metric_value"] is None:
        raise ValueError("observed result needs an explicit value")
    if record["metric"] != "OBSERVED_RESULT" and record["metric_value"] is not None:
        raise ValueError("only observed result may carry a literal value")
    if record["source_type"] == "OFFICIAL_EXPORT" and record["metric"] == "OBSERVED_RESULT":
        raise ValueError("official aggregate cannot be a literal observed result")
    if record["source_type"] == "MANUAL_OBSERVATION" and record["metric"] != "OBSERVED_RESULT":
        raise ValueError("manual observation requires its literal observation")
    if record["source_type"] == "LICENSED_EXPORT" and record["metric"] != "NO_METRIC":
        raise ValueError("licensed scope requires supplier semantics outside this worksheet")
    if record["permission"] != "PERMITTED":
        return "HOLD_PERMISSION"
    if record["device"] != "RECORDED" or record["language"] == "MISSING":
        return "HOLD_CONTEXT"
    if record["observation"] == "MISSING":
        return "MISSING_EVIDENCE"
    if record["observation"] == "NOT_PRESENT":
        return "MANUAL_REVIEW_NOT_ABSENT"
    if record["metric"] == "GSC_AVERAGE_POSITION":
        return "REPORT_COUNTRY_METRIC_ONLY"
    if record["metric"] == "OBSERVED_RESULT":
        return "REPORT_OBSERVED_CONTEXT_ONLY"
    return "MANUAL_REVIEW_NO_METRIC"


def cases():
    base = {"source_type": "OFFICIAL_EXPORT", "source_semantics": "COUNTRY_AGGREGATE", "permission": "PERMITTED",
            "country": "CA", "city": None, "device": "RECORDED",
            "language": "NOT_APPLICABLE", "timezone": "UTC", "window_start": "2026-11-01T00:00:00Z",
            "window_end": "2026-11-17T23:59:59Z", "observed_at": "2026-11-17T09:00:00Z",
            "observation": "PRESENT", "metric": "NO_METRIC", "metric_value": None}
    return (
        dict(base, id="country_export", metric="GSC_AVERAGE_POSITION", metric_value=None,
             expected="REPORT_COUNTRY_METRIC_ONLY"),
        dict(base, id="manual_context", source_type="MANUAL_OBSERVATION", source_semantics="MANUAL_CONTEXT", city="Toronto", language="RECORDED",
             metric="OBSERVED_RESULT", metric_value="top result card visible",
             expected="REPORT_OBSERVED_CONTEXT_ONLY"),
        dict(base, id="not_present", source_type="LICENSED_EXPORT", source_semantics="LICENSED_SCOPE", observation="NOT_PRESENT",
             expected="MANUAL_REVIEW_NOT_ABSENT"),
        dict(base, id="missing_context", device="MISSING", expected="HOLD_CONTEXT"),
        dict(base, id="unknown_permission", permission="UNKNOWN", expected="HOLD_PERMISSION"),
        dict(base, id="missing_evidence", observation="MISSING", expected="MISSING_EVIDENCE"),
    )


def run():
    results = []
    for case in cases():
        expected = case.pop("expected")
        actual = classify(case)
        if actual != expected:
            raise AssertionError((case["id"], actual, expected))
        results.append((case["id"], actual))
    # Counterexamples: a country aggregate is not a city rank; an unobserved
    # result is not absence; known permission/context gaps outrank a result.
    assert results[0][1] != results[1][1]
    assert results[2][1] == "MANUAL_REVIEW_NOT_ABSENT"
    assert results[3][1] == "HOLD_CONTEXT"
    assert results[4][1] == "HOLD_PERMISSION"
    bad = dict(cases()[0]); bad.pop("expected"); bad["metric"] = "OBSERVED_RESULT"
    try:
        classify(bad)
    except ValueError:
        pass
    else:
        raise AssertionError("literal observed result without value accepted")
    bad_semantics = dict(cases()[0]); bad_semantics.pop("expected"); bad_semantics["source_semantics"] = "MANUAL_CONTEXT"
    for bad_record in (bad_semantics, dict(cases()[0], expected=None, city="Toronto"),
                       dict(cases()[1], expected=None, window_start="2026-09-01T00:00:00Z")):
        bad_record.pop("expected", None)
        try:
            classify(bad_record)
        except ValueError:
            pass
        else:
            raise AssertionError("incompatible source/city/window accepted")
    return results


if __name__ == "__main__":
    results = run()
    for name, result in results:
        print("%s: %s" % (name, result))
    print("counts: %s" % dict(sorted(Counter(value for _, value in results).items())))
    print("PASS: offline synthetic records and permission/context/absence counterexamples.")
