"""Authored development examples. These are not independent human holdout data."""
from copy import deepcopy

LABELS = ("permit", "block", "review")
ABSTAIN = "__ABSTAIN__"
DOMAINS = [
    ("travel", "Replacement business travel",
     "Permit replacement travel when an unexpected transport disruption threatens a time-critical business obligation. Block upgrades or route changes made only for comfort or convenience. Require review when a request combines business recovery with personal travel or the business necessity cannot be established.",
     [
         ("permit", "The airline cancelled the only evening flight. The employee requests a train that reaches the factory before the scheduled morning safety inspection. There is no personal extension.", "Cancellation threatens a time-critical inspection; the replacement serves that obligation."),
         ("block", "The existing flight is operating and arrives before the meeting. The employee requests a premium cabin because it will be quieter and more comfortable.", "The requested change serves comfort rather than disruption recovery."),
         ("review", "After a cancelled flight, the employee requests replacement travel that would also extend the stay by two days to visit friends. The work visit still needs to happen.", "Business recovery and a personal extension are combined."),
     ]),
    ("data_release", "External data sharing",
     "Permit aggregate statistics that contain neither direct identifiers nor uncommon combinations that could identify a person. Block release of raw contact records containing names or email addresses. Require review for pseudonymous records or combinations of fields that may allow reidentification.",
     [
         ("permit", "The proposed public file contains only quarterly totals across all 100 sites. There are no person-level rows, small subgroups, names, addresses or dates associated with individuals.", "Broad aggregate totals meet the explicit release condition."),
         ("block", "The requester wants to email a spreadsheet of customers to an external partner. Each row contains the customer's full name and work email address.", "Raw contact records fall under the explicit prohibition."),
         ("review", "The export replaces names with stable worker codes, but preserves each person's minute-by-minute location history. The recipient could compare those histories with shift rosters.", "Pseudonyms and linkable histories require review."),
     ]),
    ("warranty", "Initial equipment repair",
     "Permit warranty repair for a defect present on arrival that is discovered during normal setup without misuse. Block warranty coverage for damage caused by unauthorized electrical or mechanical modification. Require review when the cause is uncertain or the evidence supports competing causes.",
     [
         ("permit", "The new unit would not power on during the first standard setup. The unopened shipping box had a crushed corner, and the case was cracked when unpacked. No modifications were made.", "The narrative supports an arrival defect without misuse."),
         ("block", "The customer bypassed the protective fuse to run the unit at a higher current. The circuit board burned immediately after that modification.", "The damage follows an unauthorized electrical modification."),
         ("review", "The unit stopped working during setup. Logs show both a factory diagnostic fault and a power interruption in the building. The inspection cannot yet distinguish the causes.", "Competing causes remain unresolved."),
     ]),
    ("software_change", "Operational change authorization",
     "Permit reversible configuration-only changes within preapproved operating limits that preserve authentication and data retention. Block changes that disable authentication or reduce required retention. Require review for schema changes, destructive backfills, irreversible operations or unclear rollback behavior.",
     [
         ("permit", "The team will lower a batch-size setting from 80 to 60 within its approved 20-to-100 range. A feature flag restores the old setting immediately. Authentication and retention are unchanged.", "The change is reversible configuration within approved limits."),
         ("block", "To avoid login failures during a demonstration, the team proposes turning off the authentication check on the production endpoint for the afternoon.", "Disabling authentication is explicitly prohibited."),
         ("review", "The migration rewrites stored customer records into a new schema. The old values will not be retained, and the team has not demonstrated a rollback.", "A destructive schema migration with unclear rollback requires review."),
     ]),
]


def build_development():
    cases = []
    for family, title, policy, narratives in DOMAINS:
        current = f"{family}-policy-v2"
        # Ordering is intentionally different from canonical ID order.
        docs = [
            {"id": f"{family}-policy-v1", "title": title + " (retired)",
             "body": "Retired rule: permit requests approved by a manager, regardless of the current exceptions. This document is historical and must be used only if explicitly referenced."},
            {"id": f"{family}-example-memo", "title": "Discussion memo: " + title,
             "body": "Staff discussed travel, release, repair and operational change requests. This memo is not the operative policy and does not authorize a decision."},
            {"id": current, "title": title + " (current route)", "body": policy},
            {"id": f"{family}-unrelated-v4", "title": "Office supply ordering",
             "body": "Permit ordering ordinary stationery within the monthly allowance. Require review for furniture and block duplicate orders."},
        ]
        refs = [{"id": f"route:{family}:north", "target": f"edition:{family}:active"},
                {"id": f"edition:{family}:active", "target": current},
                {"id": f"edition:{family}:archive", "target": f"{family}-policy-v1"}]
        for i, (label, narrative, reason) in enumerate(narratives):
            cases.append({
                "schema_version": "application-case-v1", "data_status": "development_fixture",
                "case_id": f"dev-{family}-{i}", "bundle_id": f"dev-bundle-{family}",
                "family_id": family, "organization_group": f"fictional-{family}",
                "author_group": "agent-authored-development", "split": "development",
                "documents": deepcopy(docs), "references": deepcopy(refs),
                "ticket": {"policy_ref": f"route:{family}:north", "narrative": narrative},
                "gold": {"resolution_status": "resolved", "source_id": current,
                         "source_trace": [f"route:{family}:north", f"edition:{family}:active", current],
                         "semantic_label": label, "acceptable_labels": [label],
                         "annotation_status": "development_author_oracle", "rationale": reason,
                         "serious_wrong_labels": ["permit"] if label in ("block", "review") else []},
            })
    for issue in ("missing", "cycle", "ambiguous"):
        c = deepcopy(cases[0]); c["case_id"] = f"dev-source-{issue}"
        c["bundle_id"] = f"dev-source-control-{issue}"; c["family_id"] = "source-negative-controls"
        start = c["ticket"]["policy_ref"]
        if issue == "missing": c["references"][0]["target"] = "edition:missing"
        elif issue == "cycle": c["references"][1]["target"] = start
        else: c["references"].append({"id": start, "target": "travel-policy-v1"})
        c["gold"] = {"resolution_status": issue, "source_id": None, "source_trace": None,
                     "semantic_label": None, "acceptable_labels": [],
                     "annotation_status": "development_author_oracle",
                     "rationale": "Source resolution is not uniquely defined; abstain before policy judgment.",
                     "serious_wrong_labels": []}
        cases.append(c)
    return cases
