"""is a case size a product rule or a warehouse rule?

Generated from src/content/docs/reference/discover-dependencies.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

pack_sizes = [
    ("East", "A", "Tea", 6),
    ("East", "B", "Coffee", 12),
    ("East", "C", "Cocoa", 24),
    ("West", "A", "Tea", 8),
    ("West", "B", "Coffee", 12),
    ("West", "C", "Cocoa", 24),
]
rows = []
for warehouse, sku, product, units in pack_sizes:
    for delivery in range(1, 4):
        receipt = f"{warehouse[0]}-{sku}-{delivery}"
        rows.append((receipt, warehouse, sku, product, units))

receipts = pd.DataFrame(
    rows,
    columns=[
        "receipt",
        "warehouse",
        "sku",
        "product",
        "units_per_case",
    ],
)
# Introduce one receipt that disagrees with its SKU's usual case size.
receipts.loc[receipts["receipt"] == "W-C-3", "units_per_case"] = 20
print(
    receipts.groupby(["warehouse", "sku", "units_per_case"])
    .size()
    .to_string()
)

features = ["sku", "warehouse", "units_per_case", "product"]
singles = fw.discover_dependencies(
    receipts,
    features=features,
    max_key_size=1,
    by=["warehouse"],
    min_accuracy=0.9,
    limits={"max_candidates": 4, "example_limit": 1},
)
candidates = singles.to_frame("candidates")
print(
    candidates[
        ["columns", "groups", "unique", "repeated_groups", "determines"]
    ].to_string(index=False)
)

records = [
    row
    for row in singles["dependencies"]
    if row["determinant"] == ["sku"]
    and row["target"] == "units_per_case"
]
for row in records:
    context = row["context"]
    label = "All" if context is None else context["warehouse"]
    print(
        f"{label}: {row['evaluated_rows']} rows; {row['repair_rows']} repairs; "
        f"accuracy={row['modal_accuracy']:.3f}; exact={row['exact']}"
    )

composite = fw.discover_dependencies(
    receipts,
    features=features,
    max_key_size=2,
    min_accuracy=0.9,
    limits={"max_candidates": 10, "example_limit": 1},
)
dependency_table = composite.to_frame("dependencies")
case_sizes = dependency_table[
    dependency_table["target"] == "units_per_case"
]
print(
    case_sizes[
        [
            "determinant",
            "evaluated_rows",
            "evaluated_groups",
            "violating_groups",
            "affected_rows",
            "repair_rows",
            "modal_accuracy",
        ]
    ].to_string(index=False)
)

findings = composite.to_frame("findings")
print(findings[["id", "statement"]].to_string(index=False))

exceptions = composite.inspect(
    receipts, "f4", exceptions=True, all_matches=True
)
print(
    exceptions[
        ["receipt", "sku", "warehouse", "units_per_case"]
    ].to_string(index=False)
)

product_rule = fw.discover_dependencies(
    receipts,
    features=["sku", "product"],
    max_key_size=1,
    limits={"max_candidates": 1},
)
print(
    fw.render_plaintext(
        product_rule, detail="topology", unicode_mode="display"
    )
)

sparse_receipts = pd.DataFrame(
    {"sku": ["A", "A", "B", "B"], "product": ["Tea", None, "Coffee", None]}
)
sparse = fw.discover_dependencies(
    sparse_receipts, max_key_size=1, limits={"max_candidates": 1}
)
sparse_evidence = sparse.to_frame("dependencies")
print(
    sparse_evidence[
        ["evaluated_rows", "target_coverage", "repeated_rows", "repeat_modal_accuracy"]
    ].to_string(index=False)
)

mostly_unique = pd.DataFrame(
    {"sku": list(range(99)) + [98], "product": ["Tea"] * 99 + ["Coffee"]}
)
consistency = fw.discover_dependencies(
    mostly_unique, max_key_size=1, limits={"max_candidates": 1}
)
print(
    consistency.to_frame("dependencies")[
        ["modal_accuracy", "repeat_coverage", "repeat_modal_accuracy"]
    ].to_string(index=False)
)
