"""review a parts-inspection export before grouping it

Generated from src/content/docs/reference/infer-schema.md.
Run with the documented Fieldwork release in a writable directory.
Exports are saved there using the filenames shown in the walkthrough.
"""

import pandas as pd
import fieldwork as fw

parts = pd.DataFrame(
    {
        "sample_id": [f"S{i:02d}" for i in range(1, 9)],
        "lot": ["L10", "L10", "L10", "L20", "L20", "L20", "L30", "L30"],
        "machine": ["A", "A", "A", "B", "B", "B", "A", "A"],
        "mass_g": [
            10.01,
            10.03,
            9.98,
            10.05,
            10.02,
            9.99,
            10.04,
            10.00,
        ],
        "measured_at": pd.date_range(
            "2026-05-04 08:00", periods=8, freq="min"
        ),
    }
)

proposal = fw.infer_schema(parts)
suggestions = pd.json_normalize(proposal["proposals"])
print(
    suggestions[["column", "proposed_role"]].to_string(
        index=False
    )
)

with_keys = fw.infer_schema(parts, candidate_keys=["sample_id", "lot"])
by_column = {item["column"]: item for item in with_keys["proposals"]}
print("target | candidate | holds | evaluated groups")
for column in ["machine", "mass_g"]:
    for evidence in by_column[column]["fd_evidence"]["keys"]:
        print(
            f"{column} | {evidence['name']} | {evidence['holds']} | "
            f"{evidence['evaluated_groups']}"
        )

reviewed_schema = {
    "sample_id": "id",
    "lot": "categorical",
    "machine": "categorical",
    "mass_g": "continuous",
    "measured_at": "unknown",
}
dimensions = ["lot", "machine"]
counts = fw.levels(parts, features=dimensions, schema=reviewed_schema)
print(fw.render_plaintext(counts))
