"""Check all three Assignment 4 batches before using the live site's validator."""

import json
import sys
from pathlib import Path


TOTAL_NL = 20_000
SPECS = {
    "batch_sfgfp_amp.json": ("sfGFP", "amp", {600, 550, 500, 450}, 775),
    "batch_petase_dsbc.json": ("PETase", "dsbc_ecoli", {1000, 700, 500, 300}, 1_225),
    "batch_reteplase_gsh.json": ("Reteplase", "reduced_glutathione", {200, 250, 300, 350}, 825),
}


def validate(path: Path, seen_ids: set[str]) -> None:
    target, variable, expected_levels, variable_plus_water = SPECS[path.name]
    batch = json.loads(path.read_text(encoding="utf-8"))
    assert isinstance(batch.get("experiment_hypothesis"), str)
    assert batch["experiment_hypothesis"].strip()
    samples = batch.get("samples")
    assert isinstance(samples, list) and len(samples) == len(expected_levels)

    stable_reference = None
    observed_levels = set()
    template = f"template_{target.lower()}"
    for sample in samples:
        sample_id = sample["sample_id"]
        assert isinstance(sample_id, str) and sample_id and sample_id not in seen_ids
        seen_ids.add(sample_id)
        assert sample["sample_type"] == "experimental"
        assert sample["metadata"]["protein_target"] == target
        assert sample["metadata"]["comments"].strip()

        reagents = sample["reagent_list"]
        assert isinstance(reagents, dict)
        assert all(isinstance(value, int) and value >= 0 and value % 25 == 0
                   for value in reagents.values())
        assert sum(reagents.values()) == TOTAL_NL, (sample_id, sum(reagents.values()))
        assert reagents["base_buffer"] == 2_000
        assert reagents["lysate"] == 5_000
        assert reagents[template] == 2_000
        assert all(not key.startswith("template_") or key == template for key in reagents)
        assert reagents[variable] + reagents["nuclease_free_water"] == variable_plus_water

        observed_levels.add(reagents[variable])
        stable = {key: value for key, value in reagents.items()
                  if key not in {variable, "nuclease_free_water"}}
        if stable_reference is None:
            stable_reference = stable
        assert stable == stable_reference, f"Other ingredients changed in {sample_id}"
        print(f"{sample_id}: 20,000 nL; {variable} {reagents[variable]} nL; "
              f"water {reagents['nuclease_free_water']} nL")

    assert observed_levels == expected_levels, (path.name, observed_levels)
    print(f"{path.name}: local checks passed.\n")


if __name__ == "__main__":
    base = Path(__file__).parent
    paths = ([Path(arg) for arg in sys.argv[1:]] if len(sys.argv) > 1
             else [base / filename for filename in SPECS])
    seen_ids: set[str] = set()
    for path in paths:
        validate(path, seen_ids)
