#!/usr/bin/env python3
"""One-shot real N=1 DMC dogfood launcher for DMC-FK-C3-WI01.

This is deliberately a fixed operator composition of the already accepted
Single-WorkItem Coordinator path.  It is not a generic launcher, has no retry,
and creates no new Coordinator semantics.
"""

from __future__ import annotations

import hashlib
import shutil
import subprocess
import sys
import uuid
from pathlib import Path

REPOSITORY = Path("/home/stefan/repos/spreadsheet-handling/core").resolve()
BASELINE = "f406b0d477430ab7e77ab00e9d8924fa76c6b272"
STATE_ROOT = Path("/home/stefan/wfc-runs/dmc-fk-c3-wi01-20260911-01").resolve()

WORK_ITEM_ID = "DMC-FK-C3-WI01"
HOP_ID = "H001"
TIMEOUT_SECONDS = 900.0
MODEL = "gpt-5.6-terra"
REASONING_EFFORT = "medium"
CONTEXT_MODE = "fresh / ephemeral"

ARTIFACT = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle3_supported_types_assessment_2026-09-11.adoc"
)
EXPECTED_SUBJECT = "docs(domain): DMC-FK-C3-WI01 H001 assess supported types"

DMC_PATH = "docs/developer_guide/ch06_code_conventions/05_domain_maintainer_contract.adoc"
FK_CONCEPT_PATH = "docs/ai_info/concepts_fk_helpers.adoc"
INTERFACES_PATH = "docs/ai_info/interfaces_and_gates.adoc"
GIT_WORKFLOW_PATH = "docs/ai_info/git_and_workflow.adoc"
ROADMAP_PATH = "docs/backlog/roadmap_domain_hardening_sequence.adoc"
CYCLE2_ASSESSMENT_PATH = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle2_reentry_assessment_2026-09-07.adoc"
)
CYCLE2_REVIEW_PATH = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle2_reentry_assessment_2026-09-07_review_001.adoc"
)

# The launcher is intended to live under core/tmp/, but imports the repository
# package from the exact checkout it is about to operate on.
sys.path.insert(0, str(REPOSITORY))

from scripts.workflow_coordinator.codex_adapter import CodexCliAdapter
from scripts.workflow_coordinator.model import (
    DurableArtifact,
    Phase,
    RepositoryPolicy,
    Route,
    RouteEffect,
    WorkItem,
    WorkflowProfile,
    new_run,
)
from scripts.workflow_coordinator.persistence import atomic_write_json, atomic_write_text
from scripts.workflow_coordinator.prompt import PromptComponent
from scripts.workflow_coordinator.slice4 import (
    RealHopRun,
    Slice4Error,
    register_checkout,
    run_real_one_hop,
)


TASK_PAYLOAD = f"""\
DMC-FK-C3-WI01 / H001 -- FK/reference-helper Family Cycle 3 supported-types assessment
=======================================================================================

EXECUTION BINDING
-----------------
Provider boundary: repository CodexCliAdapter
Model: {MODEL}
Reasoning effort: {REASONING_EFFORT}
Context: {CONTEXT_MODE}
Autonomous Hop budget: exactly 1
Baseline: {BASELINE}

This is a bounded real N=1 DMC dogfood WorkItem after the invocation-identity
correlation fix was implemented and independently accepted.

Family Cycle 2 is CLOSED with an accepted negative result.  This Hop begins
Family Cycle 3, "review supported types", as an ASSESSMENT ONLY.  Do not
implement type-behavior changes in this Hop.

GOAL
----
Prove what supported value/type set the FK/reference-helper family actually
declares and implements today, identify mismatches between contract,
implementation, pandas behavior, and tests, and select exactly one smallest
safe next implementation slice if the evidence supports one.

The canonical Cycle-3 goal is:

    Prove that the family behaves correctly for its declared type set and
    identify where narrower domain-specific types are required.

The objective is NOT arbitrary-Python-type support.  The objective is an
explicit supported set.

Use the roadmap's current Cycle-3 review questions as the authoritative review
frame.  In particular investigate, where relevant to this family:

- accepted scalar values in row/join keys, labels, canonical IDs, helper values,
  lookup values, and ordinary data cells;
- accidental string conversion;
- None, NaN, empty strings, unresolved values, and spreadsheet-error handling;
- equality, grouping, sorting, and hashing assumptions across heterogeneous
  values;
- date/datetime preservation or normalization;
- pandas coercion that changes the contract;
- type-specific special handling;
- whether unsupported types fail early and usefully.

READ / ANALYSIS SCOPE
---------------------
Repository-wide read/search is allowed as needed for this assessment.  Start
from current authoritative material and current source/tests, not historical
aspiration.

The DMC, FK-helper concept guidance, public-interface/gate guidance, and Git
workflow policy are already projected into this Hop by the Coordinator.

Also read fresh from the repository, at minimum:

- {ROADMAP_PATH} -- especially Family cycle 3;
- {CYCLE2_ASSESSMENT_PATH};
- {CYCLE2_REVIEW_PATH};
- docs/ai_info/_ai_info.adoc, then only additional AI-info selected as relevant;
- current canonical scalar/value, missing-value, physical-label, and Trusted
  Ingress authorities needed to establish the actual supported set;
- relevant current code under:
    src/spreadsheet_handling/domain/transformations/fk_helpers/
    src/spreadsheet_handling/domain/transformations/enrich_lookup/
    src/spreadsheet_handling/domain/validations/fk_helpers.py
  plus owner-local consumers/handoffs where required to establish type
  semantics;
- focused tests corresponding to the type behaviors you classify.

Pay explicit attention to the already-deferred Cycle-3 questions around
normalization / NaN / unresolved-value semantics in FK validation, but do not
assume those are defects before checking current authority and tests.

Do not reopen accepted global Date/Time, scalar, physical-label, Trusted
Ingress, or spreadsheet-substrate decisions merely because this family consumes
those values.  Use them as authority unless concrete current evidence shows a
family-level contradiction.

WRITE AUTHORITY
---------------
You may create or modify exactly ONE repository path:

    {ARTIFACT}

No production source, tests, FTR lifecycle, roadmap, Project Memory, registry,
AI-info, consumer pipeline, release note, or other documentation change is
authorized.

The output artifact is evidence/assessment, not binding architecture authority.
Mark implementation explicitly NOT STARTED.

REQUIRED ARTIFACT CONTENT
-------------------------
Create {ARTIFACT} with a concise but reconstructable assessment containing:

1. WorkItem/Hop identity, exact baseline, status "ASSESSMENT -- IMPLEMENTATION
   NOT STARTED", and bounded read/write scope.
2. The current authoritative type/value contracts actually relied upon, with
   references sufficient to distinguish:
      - global trusted/ingress value grammar,
      - physical-label/key authority,
      - family-specific FK/Lookup value requirements,
      - sink/adapter representation concerns.
3. A type-surface census.  For each materially distinct family role include:
      - stable local ID;
      - location / symbol / public surface;
      - semantic role (key, label, helper value, lookup value, provenance,
        validation input, etc.);
      - declared/observed supported set;
      - coercion/normalization behavior;
      - missing/unresolved behavior;
      - relevant equality/hash/group/sort assumptions;
      - current tests;
      - classification / disposition.
4. Explicitly identify every mismatch between declared contract, implementation,
   pandas/runtime behavior, and tests.  Distinguish:
      - genuine family defect;
      - missing or ambiguous contract;
      - deliberate family narrowing;
      - inherited/global behavior that is already authoritative;
      - representation/sink issue outside family ownership.
5. Select exactly ONE smallest safe next implementation slice if current
   evidence supports one.  Record likely source/test files, behavior change,
   acceptance criteria, and why it stays inside Cycle 3.
   If no implementation slice is justified, write "NO SAFE SLICE SELECTED" and
   state exactly why.
6. Record all unresolved/UNCERTAIN type questions.
7. Explicitly test the roadmap's Cycle-3 exit criteria against the family:
      - public signatures/documentation state supported values;
      - type-specific behavior tested at the appropriate domain boundary;
      - accidental coercions removed or documented;
      - special cases exist only for supported requirements.
8. Explicit non-scope and anti-drift notes.

NON-SCOPE / DO NOT DECIDE
-------------------------
Do not decide, redesign, or implement:

- arbitrary-type support;
- global scalar/value-model redesign;
- Date/Time architecture;
- spreadsheet parser/rendering substrate behavior;
- add_fk_helpers versus add_lookup_helpers public-surface consolidation;
- writable Lookup/enrichment semantics;
- formula-mode certification/redesign except where needed as read-only evidence
  for current supported types;
- package/module re-layout or shared-mechanism extraction (Cycle 4);
- general test-suite consolidation;
- new Trusted-Ingress architecture;
- Project Memory lifecycle changes;
- Workflow Coordinator implementation, Slice 5, or multi-Hop autonomy.

VALIDATION BEFORE RETURNING SUCCESS
-----------------------------------
Run:

    asciidoctor --failure-level WARN -o /dev/null {ARTIFACT}
    git diff --check
    git status --short

Before returning a successful result, verify that the only non-ignored dirty
repository path is {ARTIFACT}.

Do NOT run git add, git commit, git reset, git clean, git push, rebase, amend,
or any history rewrite.  The Coordinator owns the mechanical Git commit.

STRUCTURED RESULT ON SUCCESS
----------------------------
The generated [identity] block contains the exact run_id, hop_id, and
invocation_id for this dispatch.  Reproduce all of them exactly in the
structured-result envelope.

Return the schema-required result with exactly these semantic values:

- outcome: completed
- requested_route: complete
- scope_changed: false
- requires_human: false
- escalation: null
- findings: []
- claimed_commits: []
- commit_intent.paths: exactly ["{ARTIFACT}"]
- commit_intent.subject: exactly "{EXPECTED_SUBJECT}"
- evidence_refs: ["diff_hygiene", "git_version"]
- summary: short factual description of the supported-types assessment and
  whether one safe next slice was selected

An assessment that truthfully concludes "NO SAFE SLICE SELECTED" may still
return completed and commit the assessment artifact.  The maintainer decides
the next WorkItem after this N=1 Run.
"""


def _git(*args: str, check: bool = True) -> str:
    completed = subprocess.run(
        ("git", "-C", str(REPOSITORY), *args),
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )
    if check and completed.returncode:
        raise Slice4Error(completed.stderr.strip() or f"git {' '.join(args)} failed")
    return completed.stdout.strip()


def _git_show(path: str) -> str:
    return _git("show", f"{BASELINE}:{path}")


def _components() -> dict[str, PromptComponent]:
    return {
        "dmc_contract": PromptComponent(
            "dmc_contract", DMC_PATH, BASELINE, _git_show(DMC_PATH)
        ),
        "fk_helper_concept": PromptComponent(
            "fk_helper_concept", FK_CONCEPT_PATH, BASELINE, _git_show(FK_CONCEPT_PATH)
        ),
        "interfaces_and_gates": PromptComponent(
            "interfaces_and_gates", INTERFACES_PATH, BASELINE, _git_show(INTERFACES_PATH)
        ),
        "git_workflow": PromptComponent(
            "git_workflow", GIT_WORKFLOW_PATH, BASELINE, _git_show(GIT_WORKFLOW_PATH)
        ),
    }


def _profile() -> WorkflowProfile:
    phase = Phase(
        role="dmc_cycle3_type_assessor",
        role_components=("dmc_contract",),
        modifier_components=("fk_helper_concept", "interfaces_and_gates"),
        repository_policy_components=("git_workflow",),
        durable_artifact=DurableArtifact.REQUIRED,
        authorized_scope=(ARTIFACT,),
        authorized_actions=("edit", "commit"),
        human_gates=("scope_or_authority_change",),
        evidence=("diff_hygiene", "git_version"),
        review=None,
        routes={"complete": Route(RouteEffect.COMPLETE)},
    )
    return WorkflowProfile(
        1,
        "dmc-fk-cycle3-supported-types-n1",
        f"r1@{BASELINE}",
        {"assess": phase},
    )


def _work_item() -> WorkItem:
    return WorkItem(
        1,
        WORK_ITEM_ID,
        (
            "Maintainer one-shot authorization on 2026-09-11 to begin one "
            "bounded real N=1 DMC FK/reference-helper Cycle-3 supported-types assessment"
        ),
        "dmc-fk-cycle3-supported-types-n1",
        "core",
        (ARTIFACT,),
        "assess",
        1,
        (
            "dmc",
            "fk-reference-helper",
            "cycle-3",
            "supported-types",
            "dogfood",
            "assessment",
        ),
    )


def _policy() -> RepositoryPolicy:
    return RepositoryPolicy(
        1,
        "core-real-n1-dmc-dogfood-cycle3",
        BASELINE,
        ("core",),
        ("edit", "commit"),
        ("diff_hygiene", "git_version"),
    )


def _preflight() -> None:
    if not REPOSITORY.is_dir():
        raise Slice4Error(f"repository not found: {REPOSITORY}")

    actual_root = Path(_git("rev-parse", "--show-toplevel")).resolve()
    if actual_root != REPOSITORY:
        raise Slice4Error(
            f"repository mismatch: expected {REPOSITORY}, observed {actual_root}"
        )

    head = _git("rev-parse", "HEAD")
    if head != BASELINE:
        raise Slice4Error(
            f"baseline mismatch: expected {BASELINE}, observed {head}"
        )

    status = _git("status", "--porcelain")
    if status:
        raise Slice4Error(
            "worktree is not clean before authorization consumption:\n" + status
        )

    if STATE_ROOT.exists():
        raise Slice4Error(
            f"fixed one-shot state root already exists: {STATE_ROOT}; "
            "do not delete/reuse it"
        )

    if (REPOSITORY / ARTIFACT).exists():
        raise Slice4Error(
            f"authorized output path already exists in worktree: {ARTIFACT}"
        )

    tracked = subprocess.run(
        (
            "git",
            "-C",
            str(REPOSITORY),
            "cat-file",
            "-e",
            f"{BASELINE}:{ARTIFACT}",
        ),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        check=False,
    )
    if tracked.returncode == 0:
        raise Slice4Error(
            f"authorized output path already exists at baseline: {ARTIFACT}"
        )

    if shutil.which("codex") is None:
        raise Slice4Error("codex executable is not on PATH")

    adapter_probe = CodexCliAdapter(Path("/tmp/wfc-config-probe"))
    if (
        adapter_probe.model != MODEL
        or adapter_probe.reasoning_effort != REASONING_EFFORT
    ):
        raise Slice4Error(
            "CodexCliAdapter defaults drifted from this authorization: "
            f"model={adapter_probe.model!r}, "
            f"reasoning={adapter_probe.reasoning_effort!r}"
        )


def _git_facts() -> dict[str, object]:
    final_head = _git("rev-parse", "HEAD", check=False)

    commits = _git(
        "rev-list",
        "--reverse",
        f"{BASELINE}..{final_head}",
        check=False,
    ).splitlines()

    return {
        "baseline": BASELINE,
        "final_head": final_head,
        "actual_commits": commits,
        "actual_commit_subjects": [
            _git(
                "show",
                "-s",
                "--format=%s",
                commit,
                check=False,
            )
            for commit in commits
            if commit
        ],
        "committed_changed_paths": _git(
            "diff",
            "--name-only",
            f"{BASELINE}..{final_head}",
            check=False,
        ).splitlines(),
        "git_status_porcelain": _git(
            "status",
            "--porcelain",
            check=False,
        ),
    }


def _write_launch_inputs(
    *,
    components: dict[str, PromptComponent],
    run_id: str,
    invocation_id: str,
) -> None:
    launcher_text = Path(__file__).read_text(encoding="utf-8")

    atomic_write_text(
        STATE_ROOT / "launcher-source.py",
        launcher_text,
    )

    atomic_write_text(
        STATE_ROOT / "task-payload.txt",
        TASK_PAYLOAD,
    )

    atomic_write_json(
        STATE_ROOT / "launch-plan.json",
        {
            "schema_version": 1,
            "one_shot": True,
            "retry_authorized": False,
            "work_item_id": WORK_ITEM_ID,
            "hop_id": HOP_ID,
            "run_id": run_id,
            "invocation_id": invocation_id,
            "repository": str(REPOSITORY),
            "baseline": BASELINE,
            "state_root": str(STATE_ROOT),
            "authorized_write_scope": [ARTIFACT],
            "durable_artifact": ARTIFACT,
            "expected_commit_subject": EXPECTED_SUBJECT,
            "max_autonomous_hops": 1,
            "provider_executable": "codex",
            "model": MODEL,
            "reasoning_effort": REASONING_EFFORT,
            "context": CONTEXT_MODE,
            "timeout_seconds": TIMEOUT_SECONDS,
            "permitted_routes": ["complete"],
            "selected_prompt_components": [
                component.reference()
                for component in components.values()
            ],
            "roadmap_read_reference": (
                f"git show {BASELINE}:{ROADMAP_PATH}"
            ),
            "cycle2_assessment_read_reference": (
                f"git show {BASELINE}:{CYCLE2_ASSESSMENT_PATH}"
            ),
            "cycle2_review_read_reference": (
                f"git show {BASELINE}:{CYCLE2_REVIEW_PATH}"
            ),
            "launcher_sha256": hashlib.sha256(
                launcher_text.encode("utf-8")
            ).hexdigest(),
            "no_push": True,
        },
    )


def _summary(
    *,
    real_hop: RealHopRun | None,
    error: str | None,
    run_id: str,
    invocation_id: str,
    checkout_id: str | None,
) -> dict[str, object]:
    facts = _git_facts()
    final_run = real_hop.run if real_hop is not None else None
    outcome = real_hop.outcome if real_hop is not None else None

    return {
        "schema_version": 1,
        "work_item_id": WORK_ITEM_ID,
        "hop_id": HOP_ID,
        "run_id": run_id,
        "invocation_id": invocation_id,
        "checkout_id": checkout_id,
        "state_root": str(STATE_ROOT),
        "artifact": ARTIFACT,
        "expected_commit_subject": EXPECTED_SUBJECT,
        "model": MODEL,
        "reasoning_effort": REASONING_EFFORT,
        "context": CONTEXT_MODE,
        "timeout_seconds": TIMEOUT_SECONDS,
        **facts,
        "run_status": (
            final_run.status.value if final_run else None
        ),
        "hop_used": (
            final_run.hop_used if final_run else 0
        ),
        "hop_limit": (
            final_run.hop_limit if final_run else 1
        ),
        "stop_reason": (
            final_run.stop_reason if final_run else None
        ),
        "human_question": (
            final_run.human_question if final_run else None
        ),
        "anomalies": (
            list(final_run.anomalies) if final_run else []
        ),
        "vertical_success": bool(
            real_hop is not None and real_hop.vertical is not None
        ),
        "process_returncode": (
            outcome.returncode if outcome else None
        ),
        "timed_out": (
            outcome.timed_out if outcome else False
        ),
        "diagnostics": (
            list(outcome.diagnostics) if outcome else []
        ),
        "candidate_result_present": bool(
            outcome and outcome.candidate_result
        ),
        "operator_error": error,
    }


def _success(summary: dict[str, object]) -> bool:
    return (
        summary["operator_error"] is None
        and summary["vertical_success"] is True
        and summary["run_status"] == "completed"
        and summary["hop_used"] == 1
        and summary["git_status_porcelain"] == ""
        and summary["actual_commit_subjects"] == [EXPECTED_SUBJECT]
        and summary["committed_changed_paths"] == [ARTIFACT]
    )


def main() -> int:
    # Everything before STATE_ROOT creation is local pre-provider validation.
    # Once the fixed attempt root is created, never reuse it for a retry.
    try:
        _preflight()
    except Exception as error:
        print(
            f"PRE-FLIGHT STOP: {type(error).__name__}: {error}",
            file=sys.stderr,
        )
        return 2

    components = _components()
    profile = _profile()
    work_item = _work_item()
    policy = _policy()

    run_id = f"RUN-{uuid.uuid4().hex}"
    invocation_id = f"INV-{uuid.uuid4().hex}"

    run = new_run(
        work_item,
        profile,
        policy,
        run_id=run_id,
        baseline_head=BASELINE,
    )

    # Reserve the fixed one-shot attempt root only after all local configuration
    # has been validated.  Never delete/reuse this root for a retry.
    STATE_ROOT.mkdir(
        parents=True,
        exist_ok=False,
    )

    _write_launch_inputs(
        components=components,
        run_id=run_id,
        invocation_id=invocation_id,
    )

    real_hop: RealHopRun | None = None
    error_text: str | None = None
    checkout_id: str | None = None

    try:
        association = register_checkout(
            STATE_ROOT,
            REPOSITORY,
        )
        checkout_id = association.checkout_id

        # EXACTLY ONE provider-capable call.
        # There is deliberately no retry, resume, loop, alternate root,
        # or second invocation in this launcher.
        real_hop = run_real_one_hop(
            run,
            profile,
            REPOSITORY,
            components,
            state_root=STATE_ROOT,
            association=association,
            task_payload=TASK_PAYLOAD,
            invocation_id=invocation_id,
            timeout_seconds=TIMEOUT_SECONDS,
            executable="codex",
            durable_artifacts=(ARTIFACT,),
        )

    except Exception as error:
        error_text = f"{type(error).__name__}: {error}"

    summary = _summary(
        real_hop=real_hop,
        error=error_text,
        run_id=run_id,
        invocation_id=invocation_id,
        checkout_id=checkout_id,
    )

    summary_path = STATE_ROOT / "operator-summary.json"
    atomic_write_json(
        summary_path,
        summary,
    )

    print(f"STATE ROOT: {STATE_ROOT}")

    if checkout_id:
        print(
            "RUN ROOT: "
            f"{STATE_ROOT / 'checkouts' / checkout_id}"
        )

    print(f"SUMMARY: {summary_path}")
    print(f"RUN STATUS: {summary['run_status']}")
    print(
        f"HOP USED: "
        f"{summary['hop_used']}/{summary['hop_limit']}"
    )

    if summary["operator_error"]:
        print(
            f"OPERATOR ERROR: "
            f"{summary['operator_error']}"
        )

    last_commit = _git(
        "log",
        "-1",
        "--format=%H %s",
        check=False,
    )

    print(f"LAST COMMIT: {last_commit}")
    print(f"CURRENT HEAD: {summary['final_head']}")

    print(
        "WORKTREE CLEAN: "
        f"{'YES' if summary['git_status_porcelain'] == '' else 'NO'}"
    )

    return 0 if _success(summary) else 1


if __name__ == "__main__":
    raise SystemExit(main())
