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

This is a fixed operator composition of the accepted Single-WorkItem
Coordinator path. It is deliberately 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 = "78ca2f833e2b9e2cc2ca1dcdb7825b61a3efcb5e"
STATE_ROOT = Path("/home/stefan/wfc-runs/dmc-fk-c3-s1-20260911-01").resolve()

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

SOURCE_PATH = "src/spreadsheet_handling/domain/validations/fk_helpers.py"
TEST_PATH = "tests/unit/domain/validations/test_fk_check.py"
AUTHORIZED_PATHS = (SOURCE_PATH, TEST_PATH)

EXPECTED_SUBJECT = "fix(domain): DMC-FK-C3-S1 H001 align FK missing validation"

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"

ASSESSMENT_PATH = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle3_supported_types_assessment_2026-09-11.adoc"
)
REVIEW_PATH = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle3_supported_types_assessment_2026-09-11_review_001.adoc"
)

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-S1 / H001 -- implement narrowed Cycle-3 FK Missing-validation slice
================================================================================

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 implementation WorkItem in FK/reference-helper
Family Cycle 3 ("review supported types").

The preceding Cycle-3 assessment was independently reviewed with verdict B and
then narrowed exactly as required. The accepted implementation scope is now:

    check_unresolvable_fks
    check_helper_values

ONLY.

check_duplicate_ids is explicitly OUT OF SCOPE. Its Missing target-key identity
semantics remain UNDECIDED.

GOAL
----
Implement the accepted C3-S1 correction so FK validation consistently uses the
already-authoritative Missing-carrier predicate for the two authorized
validation functions, without changing any unresolved non-missing key-domain,
trimming, equality, duplicate-ID, enrichment, Lookup, or adapter semantics.

READ FIRST / AUTHORITY
----------------------
Read current repository state at this baseline, especially:

- {ASSESSMENT_PATH}
  - current narrowed C3-S1 section and acceptance criteria;
- {REVIEW_PATH}
  - verdict B, BLOCKER-1 resolution contract, FINDING-2, and WATCH-1;
- current {SOURCE_PATH};
- current {TEST_PATH};
- `src/spreadsheet_handling/core/scalar_values.py`, especially
  `is_missing_carrier`;
- the sibling use of `is_missing_carrier` in
  `src/spreadsheet_handling/domain/validations/reference_validations.py`;
- focused FK validation / primitive tests as needed for read-only context.

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

IMPLEMENTATION CONTRACT
-----------------------

1. `check_unresolvable_fks`

   Make supported Missing source-FK carriers produce no unresolvable-FK finding.

   The accepted Missing set includes:

   - `None`
   - empty string `""`
   - float / NumPy NaN
   - `pd.NA`
   - `NaT`

   Literal string `"nan"` is NOT Missing and must remain an ordinary String. If
   it does not resolve, it must still be reported.

   A non-missing unresolved FK must remain a finding.

2. `check_helper_values`

   A Missing source FK must not be falsely compared against helper/target
   payload. Use the same accepted Missing-carrier authority for the skip
   decision.

   Existing successful target-payload comparison and accepted unresolved-helper
   behavior must remain unchanged.

3. Preserve non-missing normalization behavior

   The independent review explicitly warned against replacing the whole local
   normalizer with `is_missing_carrier`.

   Do NOT accidentally change existing `str(...).strip()` behavior for
   non-missing values. C3-S1 changes Missing recognition only.

4. `check_duplicate_ids` MUST remain behaviorally and textually unchanged.

   Do not modify its `astype("string")`, `value_counts`, `"nan"` guard, finding
   construction, or surrounding duplicate-ID behavior.

   Current behavior can report multiple Missing target IDs as duplicates.
   Whether that is correct is an UNDECIDED target-key identity policy question
   and is deliberately not solved here.

5. Do not change FK enrichment/materialization, Lookup behavior, policy,
   provenance, adapters, scalar authority, or public signatures.

WRITE AUTHORITY
---------------
You may create/modify exactly these TWO tracked repository paths:

    {SOURCE_PATH}
    {TEST_PATH}

No other path is authorized.

In particular, do NOT modify:

- `check_duplicate_ids` semantics inside {SOURCE_PATH};
- assessment/review documentation;
- roadmap or Project Memory;
- FK/Lookup transformation code;
- core scalar-value authority;
- Workflow Coordinator files;
- release notes.

TEST REQUIREMENTS
-----------------
Add focused regressions in {TEST_PATH} that prove, at minimum:

- `check_unresolvable_fks` ignores every supported Missing source-FK carrier:
  `None`, `""`, float/NumPy NaN, `pd.NA`, `NaT`;
- literal `"nan"` remains non-missing and is reported when unresolved;
- an ordinary non-missing unresolved FK remains reported;
- `check_helper_values` does not falsely compare Missing source FKs;
- ordinary successful helper-value validation remains unchanged;
- no test asserts or changes a policy for Missing target IDs in
  `check_duplicate_ids`.

Prefer the smallest test construction already idiomatic in the existing test
file. Do not create a generic type-matrix abstraction unless it is clearly
smaller than direct parametrization.

VALIDATION BEFORE RETURNING SUCCESS
-----------------------------------
Run at least:

    .venv/bin/pytest -q tests/unit/domain/validations/test_fk_check.py
    .venv/bin/pytest -q tests/unit/domain/transformations/test_fk_helper_primitives_policy_driven.py
    .venv/bin/ruff check {SOURCE_PATH} {TEST_PATH}
    git diff --check
    git status --short

Inspect the final diff and verify:

- only {SOURCE_PATH} and {TEST_PATH} are dirty;
- `check_duplicate_ids` has no diff;
- no new key/string/trim/equality policy was introduced.

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.

IF THE SLICE CANNOT BE IMPLEMENTED SAFELY
-----------------------------------------
Do not broaden scope and do not guess a semantic rule.

Return a structured result that requests human attention with an appropriate
`semantic_authority` or `scope` escalation, no commit intent, and a concise
explanation. The one-shot remains consumed if the provider boundary was
reached.

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
  ["{SOURCE_PATH}", "{TEST_PATH}"]
- commit_intent.subject: exactly
  "{EXPECTED_SUBJECT}"
- evidence_refs: ["diff_hygiene", "git_version"]
- summary: short factual description of the Missing-validation implementation
  and focused regression coverage

The maintainer will obtain an independent implementation review after this N=1
Run. This Hop does not self-accept the implementation.
"""


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_fk_missing_implementer",
        role_components=("dmc_contract",),
        modifier_components=("fk_helper_concept", "interfaces_and_gates"),
        repository_policy_components=("git_workflow",),
        durable_artifact=DurableArtifact.NONE,
        authorized_scope=AUTHORIZED_PATHS,
        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-s1-implementation-n1",
        f"r1@{BASELINE}",
        {"implement": phase},
    )


def _work_item() -> WorkItem:
    return WorkItem(
        1,
        WORK_ITEM_ID,
        (
            "Maintainer one-shot authorization on 2026-09-11 to implement the "
            "independently reviewed and narrowed DMC FK/reference-helper Cycle-3 "
            "slice C3-S1"
        ),
        "dmc-fk-cycle3-s1-implementation-n1",
        "core",
        AUTHORIZED_PATHS,
        "implement",
        1,
        (
            "dmc",
            "fk-reference-helper",
            "cycle-3",
            "supported-types",
            "c3-s1",
            "implementation",
            "dogfood",
        ),
    )


def _policy() -> RepositoryPolicy:
    return RepositoryPolicy(
        1,
        "core-real-n1-dmc-dogfood-cycle3-s1",
        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"
        )

    for path in AUTHORIZED_PATHS:
        worktree_path = REPOSITORY / path
        if not worktree_path.is_file():
            raise Slice4Error(f"authorized tracked path is missing: {path}")
        tracked = subprocess.run(
            (
                "git",
                "-C",
                str(REPOSITORY),
                "cat-file",
                "-e",
                f"{BASELINE}:{path}",
            ),
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
        )
        if tracked.returncode != 0:
            raise Slice4Error(
                f"authorized path is not tracked at baseline: {path}"
            )

    for authority_path in (ASSESSMENT_PATH, REVIEW_PATH):
        tracked = subprocess.run(
            (
                "git",
                "-C",
                str(REPOSITORY),
                "cat-file",
                "-e",
                f"{BASELINE}:{authority_path}",
            ),
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
        )
        if tracked.returncode != 0:
            raise Slice4Error(
                f"required authority artifact missing at baseline: {authority_path}"
            )

    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": list(AUTHORIZED_PATHS),
            "durable_artifact": None,
            "assessment_authority": ASSESSMENT_PATH,
            "review_authority": REVIEW_PATH,
            "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()
            ],
            "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),
        "authorized_write_scope": list(AUTHORIZED_PATHS),
        "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"] == list(AUTHORIZED_PATHS)
    )


def main() -> int:
    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,
    )

    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.
        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=(),
        )

    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())
