"""which facts belong to a book, an edition, or a copy?

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

# Each edition has two physical copies. Edition and copy numbers are local.
editions = [
    ("W1", "Night Ferries", 1, "hardback", 2018),
    ("W1", "Night Ferries", 2, "paperback", 2021),
    ("W2", "Salt Atlas", 1, "hardback", 2019),
    ("W2", "Salt Atlas", 2, "paperback", 2022),
    ("W3", "Small Weather", 1, "paperback", 2020),
    ("W3", "Small Weather", 2, "hardback", 2023),
]
rows = []
for work, title, edition, binding, year in editions:
    for copy, condition in [(1, "good"), (2, "worn")]:
        rows.append(
            (work, title, edition, copy, binding, year, condition)
        )

catalog = pd.DataFrame(
    rows,
    columns=[
        "work",
        "title",
        "edition",
        "copy",
        "binding",
        "year",
        "condition",
    ],
)
print(f"Rows: {len(catalog)}; works: {catalog['work'].nunique()}")
print("Edition numbers:", sorted(catalog["edition"].unique().tolist()))

keys = [
    fw.KeySpec("work", ("work",)),
    fw.KeySpec("edition", ("work", "edition")),
    fw.KeySpec("copy", ("work", "edition", "copy")),
]
result = fw.grain(catalog, candidate_keys=keys)

dependencies = result.to_frame("dependencies")
columns = [
    "key_name",
    "target",
    "holds",
    "evaluated_groups",
    "repeated_groups",
    "singleton_groups",
]
print(dependencies[columns].to_string(index=False))

targets = result.to_frame("targets")
print(
    targets[["target", "coarsest_candidates"]].to_string(index=False)
)
svg = fw.render_svg(result, view="map")

# A paperback label appears on the second copy of W2's first edition.
questionable = catalog.copy()
changed = (
    (questionable["work"] == "W2")
    & (questionable["edition"] == 1)
    & (questionable["copy"] == 2)
)
questionable.loc[changed, "binding"] = "paperback"
review = fw.grain(questionable, candidate_keys=keys)
review_table = review.to_frame("dependencies")
binding_check = review_table.loc[
    (review_table["key_name"] == "edition")
    & (review_table["target"] == "binding")
].iloc[0]
print(
    f"Edition -> binding: holds={binding_check['holds']}; "
    f"violating groups={binding_check['violating_groups']}/{binding_check['evaluated_groups']}; "
    f"affected rows={binding_check['affected_rows']}/{binding_check['evaluated_rows']}"
)
print(
    questionable.loc[
        (questionable["work"] == "W2") & (questionable["edition"] == 1),
        ["work", "edition", "copy", "binding"],
    ].to_string(index=False)
)
review_targets = review.to_frame("targets")
binding_target = review_targets[review_targets["target"] == "binding"]
print(
    binding_target[["target", "coarsest_candidates"]].to_string(
        index=False
    )
)

from pathlib import Path

Path("grain.svg").write_text(svg, encoding="utf-8")
Path("grain.html").write_text(fw.render_html(review), encoding="utf-8")
