"""Small dependency-free checks for the Pixel Echo dataset/benchmark scaffold.

This is a structural and split-policy validator. It deliberately does not
download data, inspect model weights, compute cryptographic digests, or claim
to prove acquisition chronology.
"""

from __future__ import annotations

import json
import math
from pathlib import Path
from typing import Any, Iterable


ROOT = Path(__file__).resolve().parent


def _required(record: dict[str, Any], keys: Iterable[str], label: str) -> list[str]:
    return [f"{label}: missing {key}" for key in keys if key not in record]


def _nonempty(record: dict[str, Any], key: str, label: str) -> list[str]:
    value = record.get(key)
    if not isinstance(value, str) or not value.strip():
        return [f"{label}: {key} must be a non-empty string"]
    return []


def _resolution(record: dict[str, Any], label: str) -> list[str]:
    value = record.get("native_resolution")
    if not isinstance(value, dict):
        return [f"{label}: native_resolution must be an object"]
    errors: list[str] = []
    for key in ("width", "height"):
        if not isinstance(value.get(key), int) or value[key] < 1:
            errors.append(f"{label}: native_resolution.{key} must be positive")
    return errors


def validate_mechanism_sample(record: dict[str, Any], label: str = "sample") -> list[str]:
    required = (
        "schema_version", "dataset_kind", "sample_id", "mechanism_id",
        "mechanism_group_id", "cohort_id", "cohort_role", "split", "task",
        "generator_id", "decoder_id", "checkpoint_identity", "condition_id",
        "native_resolution", "native_mime_type", "export_pipeline_id",
        "transformations", "label_visibility",
    )
    errors = _required(record, required, label)
    if errors:
        return errors
    errors += _nonempty(record, "sample_id", label)
    errors += _nonempty(record, "mechanism_group_id", label)
    errors += _nonempty(record, "cohort_id", label)
    errors += _nonempty(record, "condition_id", label)
    errors += _nonempty(record, "export_pipeline_id", label)
    if record["schema_version"] != "mechanism_sample_v1":
        errors.append(f"{label}: unsupported mechanism schema_version")
    if record["dataset_kind"] != "mechanism":
        errors.append(f"{label}: dataset_kind must be mechanism")
    if record["split"] != "mechanism":
        errors.append(f"{label}: mechanism samples cannot use benchmark splits")
    if record["mechanism_id"] not in {"c2i_mechanism_1k", "t2i_mechanism_1k"}:
        errors.append(f"{label}: unknown mechanism_id")
    if record["cohort_role"] not in {"REAL", "RECON", "GEN"}:
        errors.append(f"{label}: unknown cohort_role")
    if record["task"] not in {"C2I", "T2I"}:
        errors.append(f"{label}: task must be C2I or T2I")
    if record["cohort_role"] == "REAL":
        if record["generator_id"] is not None or record["decoder_id"] is not None:
            errors.append(f"{label}: REAL cannot claim a generator or decoder")
    elif not isinstance(record["generator_id"], str) or not record["generator_id"]:
        errors.append(f"{label}: RECON/GEN needs an explicit generator_id")
    if not isinstance(record["transformations"], list):
        errors.append(f"{label}: transformations must be a list")
    if record["label_visibility"] != "public_mechanism_metadata":
        errors.append(f"{label}: mechanism labels must be public_mechanism_metadata")
    errors += _resolution(record, label)
    return errors


def validate_benchmark_sample(record: dict[str, Any], label: str = "sample") -> list[str]:
    required = (
        "schema_version", "dataset_kind", "sample_id", "cohort_id", "split",
        "task", "is_generated", "generator_id", "decoder_id", "condition_id",
        "native_resolution", "native_mime_type", "export_pipeline_id",
        "transformations", "label_visibility",
    )
    errors = _required(record, required, label)
    if errors:
        return errors
    for key in ("sample_id", "cohort_id", "condition_id", "export_pipeline_id"):
        errors += _nonempty(record, key, label)
    if record["schema_version"] != "benchmark_sample_v1":
        errors.append(f"{label}: unsupported benchmark schema_version")
    if record["dataset_kind"] != "benchmark":
        errors.append(f"{label}: dataset_kind must be benchmark")
    if record["split"] not in {"train", "validation", "private_test"}:
        errors.append(f"{label}: invalid benchmark split")
    if record["task"] not in {"real_vs_gen", "generator_attribution", "decoder_attribution"}:
        errors.append(f"{label}: invalid benchmark task")
    if not isinstance(record["transformations"], list):
        errors.append(f"{label}: transformations must be a list")
    errors += _resolution(record, label)

    public_label = record["label_visibility"] == "public_label"
    unlabeled = record["label_visibility"] == "public_unlabeled"
    private_label = record["label_visibility"] == "private_label"
    if not (public_label or unlabeled or private_label):
        errors.append(f"{label}: invalid label_visibility")
    if record["split"] == "private_test" and public_label:
        errors.append(f"{label}: private_test labels cannot be public")
    if unlabeled:
        for key in ("is_generated", "generator_id", "decoder_id", "prompt_id", "class_id", "seed"):
            if record.get(key) is not None:
                errors.append(f"{label}: unlabeled record exposes {key}")
    if public_label or private_label:
        if not isinstance(record["is_generated"], bool):
            errors.append(f"{label}: labelled record needs boolean is_generated")
        elif record["is_generated"] and not record.get("generator_id"):
            errors.append(f"{label}: generated record needs generator_id")
        elif not record["is_generated"] and record.get("generator_id") is not None:
            errors.append(f"{label}: REAL record cannot claim generator_id")
    if record["task"] == "decoder_attribution" and not record.get("decoder_id") and not unlabeled:
        errors.append(f"{label}: decoder_attribution needs decoder_id in evaluator labels")
    return errors


def validate_cohort_manifest(manifest: dict[str, Any], label: str = "manifest") -> list[str]:
    required = ("schema_version", "manifest_id", "dataset_kind", "status", "cohort_id", "task", "role", "split_policy", "samples")
    errors = _required(manifest, required, label)
    if errors:
        return errors
    if manifest["schema_version"] != "cohort_manifest_v1":
        errors.append(f"{label}: unsupported schema_version")
    if manifest["status"] not in {"DESIGN_ONLY", "ACQUISITION_PENDING", "ACQUIRED", "RELEASE_CANDIDATE", "PRIVATE_TEST"}:
        errors.append(f"{label}: invalid status")
    if not isinstance(manifest["samples"], list) or any(not isinstance(x, str) or not x for x in manifest["samples"]):
        errors.append(f"{label}: samples must be a list of non-empty IDs")
    if manifest["dataset_kind"] == "mechanism" and manifest["task"] not in {"C2I", "T2I"}:
        errors.append(f"{label}: mechanism task must be C2I or T2I")
    if manifest["dataset_kind"] == "benchmark" and manifest["task"] not in {"real_vs_gen", "generator_attribution", "decoder_attribution"}:
        errors.append(f"{label}: benchmark task is invalid")
    return errors


def validate_submission_rows(rows: Iterable[dict[str, Any]]) -> list[str]:
    errors: list[str] = []
    seen: set[tuple[str, str]] = set()
    for index, row in enumerate(rows):
        label = f"submission[{index}]"
        required = ("schema_version", "sample_id", "task_id", "prediction")
        errors += _required(row, required, label)
        if any(error.startswith(label + ": missing") for error in errors[-len(required):]):
            continue
        if row["schema_version"] != "submission_v1":
            errors.append(f"{label}: unsupported schema_version")
        task = row["task_id"]
        if task not in {"real_vs_gen", "generator_attribution", "decoder_attribution"}:
            errors.append(f"{label}: invalid task_id")
        key = (str(row["sample_id"]), str(task))
        if key in seen:
            errors.append(f"{label}: duplicate sample_id/task_id")
        seen.add(key)
        prediction = row["prediction"]
        if task == "real_vs_gen":
            if not isinstance(prediction, (int, float)) or isinstance(prediction, bool) or not math.isfinite(float(prediction)) or not 0 <= float(prediction) <= 1:
                errors.append(f"{label}: real_vs_gen prediction must be a finite probability")
        elif isinstance(prediction, dict):
            if not prediction:
                errors.append(f"{label}: attribution probability map is empty")
            for name, value in prediction.items():
                if not isinstance(name, str) or not name or not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(float(value)) or not 0 <= float(value) <= 1:
                    errors.append(f"{label}: invalid attribution probability for {name!r}")
        elif not isinstance(prediction, str) or not prediction:
            errors.append(f"{label}: attribution prediction must be a label or probability map")
    return errors


def load_json(path: str | Path) -> Any:
    return json.loads(Path(path).read_text(encoding="utf-8"))


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", type=Path)
    parser.add_argument("--kind", choices=("mechanism", "benchmark", "manifest"), required=True)
    args = parser.parse_args()
    value = load_json(args.path)
    if args.kind == "mechanism":
        problems = validate_mechanism_sample(value, str(args.path))
    elif args.kind == "benchmark":
        problems = validate_benchmark_sample(value, str(args.path))
    else:
        problems = validate_cohort_manifest(value, str(args.path))
    if problems:
        for problem in problems:
            print(problem)
        raise SystemExit(1)
    print(f"OK: {args.path}")
