"""Explicit reviewed names, exact live-schema binding and feature-bundle placebo."""
from __future__ import annotations
from copy import deepcopy
import numpy as np
from s34_data import json_hash

VIEWS = ("student", "course", "history")


def bind_manifest(names, catalog, bundles):
    names = list(names)
    if len(names) != len(set(names)):
        raise ValueError("Duplicate input feature names")
    expected = catalog.get("input_feature_names", [])
    if expected and expected != names:
        raise ValueError("Explicit manifest input_feature_names differs from live schema")
    assigned = sum([catalog.get(v, []) for v in VIEWS], [])
    if len(assigned) != len(set(assigned)):
        raise ValueError("Feature assigned to more than one semantic view")
    m = {v: [n for n in names if n in catalog.get(v, [])] for v in VIEWS}
    m["full_path_only"] = [n for n in names if n not in set(sum(m.values(), []))]
    if any(not m[v] for v in VIEWS):
        raise ValueError("Empty semantic view after binding; inspect live feature manifest")
    if set(bundles) != set(names):
        raise ValueError("Preprocessing bundle schema mismatch")
    m.update(schema_version=1, input_feature_names=names,
             semantic_review_status="REVIEWED_CATALOG_BOUND_TO_LIVE_SCHEMA",
             provenance_notes=catalog.get("provenance_notes", {}),
             categorical=[n for n in catalog.get("categorical", []) if n in names])
    reviewed = set(assigned + catalog.get("full_path_only", []))
    m["unreviewed_live_features"] = [n for n in names if n not in reviewed]
    if m["unreviewed_live_features"]:
        m["semantic_review_status"] = "REVIEWED_CATALOG_WITH_UNREVIEWED_FULL_PATH_FIELDS"
    m["schema_hash"] = json_hash(m)
    return m


def view_indices(manifest, bundles):
    return {v: sum([bundles[n] for n in manifest[v]], []) for v in VIEWS}


def randomize_manifest(manifest, bundles, seed):
    result = deepcopy(manifest)
    rng = np.random.default_rng(seed)
    eligible = sum([manifest[v] for v in VIEWS], [])
    for v in VIEWS:
        result[v] = []
    for width in sorted({len(bundles[n]) for n in eligible}):
        pool = [n for n in eligible if len(bundles[n]) == width]
        rng.shuffle(pool)
        offset = 0
        for v in VIEWS:
            count = sum(len(bundles[n]) == width for n in manifest[v])
            result[v] += pool[offset:offset+count]
            offset += count
    # Canonical feature ordering inside each view removes order-only effects.
    for v in VIEWS:
        result[v] = [n for n in manifest["input_feature_names"] if n in result[v]]
    result["partition_seed"] = int(seed)
    result["semantic_review_status"] = "LABEL_FREE_RANDOM_BUNDLE_PLACEBO"
    result.pop("schema_hash", None)
    result["schema_hash"] = json_hash(result)
    return result
