#!/usr/bin/env python3
"""One-shot real N=1 DMC dogfood launcher for DMC-FK-C2-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 = "02f98bf176042a6b32258d75afdb1a63fdab76ec"
STATE_ROOT = Path("/home/stefan/wfc-runs/dmc-fk-c2-wi01-20260907-01").resolve()

WORK_ITEM_ID = "DMC-FK-C2-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_cycle2_reentry_assessment_2026-09-07.adoc"
)
EXPECTED_SUBJECT = "docs(domain): DMC-FK-C2-WI01 H001 assess cycle 2 guards"

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"
CYCLE1_CLOSURE_PATH = (
    "docs/warm_storage/global_reviews/"
    "domain_fk_reference_helper_family_cycle1_closure_assessment_2026-08-25_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-C2-WI01 / H001 -- FK/reference-helper Family Cycle 2 re-entry 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 the first bounded real N=1 DMC dogfood WorkItem.  It begins Family
Cycle 2 as an ASSESSMENT ONLY.  Do not implement a Cycle-2 removal in this Hop.

GOAL
----
Perform a bounded re-entry assessment for the FK/reference-helper family under
Family Cycle 2, "remove redundant security defensive logic".  Inventory material
local defensive checks, determine which responsibilities are now owned by
mandatory Trusted Ingress and which remain legitimate family/sink invariants,
and select the smallest safe implementation slice that should be authorized
next.

The roadmap's Cycle-2 classification is authoritative:

- business or transformation invariant -> keep in the family;
- conformant-value/type invariant guaranteed by ingress -> remove from family;
- historical guard for an unreachable payload -> remove with redundant test;
- output-sink security responsibility -> move or retain at the sink.

Use an additional UNCERTAIN classification when current authority or reachability
evidence is insufficient.  Do not guess.

READ / ANALYSIS SCOPE
---------------------
Repository-wide read/search is allowed as needed for this assessment.  Start
from current authoritative material and inspect current execution paths, 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 2;
- {CYCLE1_CLOSURE_PATH};
- docs/ai_info/_ai_info.adoc, then only additional AI-info selected as relevant;
- current canonical Trusted-Ingress documentation needed to prove what ingress
  actually guarantees, especially the Developer/Technical Model material;
- 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 direct current handoffs/consumers only where needed to establish
  ownership or reachability;
- focused tests corresponding to the checks you classify.

Do not treat an old FTR/review statement as current runtime truth when current
canonical docs or execution paths disagree.

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 the bounded read/write scope.
2. The specific Trusted-Ingress guarantees actually relied upon, with current
   authority references and enough execution-path evidence to distinguish a
   real mandatory guarantee from merely intended policy.
3. A census table of the material defensive checks found in the bounded family
   area.  For each include at least:
      - stable local ID;
      - location / symbol;
      - protected condition or failure mode;
      - classification;
      - evidence / authority reason;
      - disposition.
4. For every item classified as ingress-redundant or historical-unreachable,
   identify the focused tests that currently encode the redundant behavior and
   what would need to change if that guard were removed.
5. Select exactly ONE smallest safe next implementation slice if the evidence
   supports one.  Record likely source/test files, expected deletion or
   simplification, acceptance criteria, and why supported public behavior does
   not change.  If current evidence does NOT support a safe slice, write
   "NO SAFE SLICE SELECTED" and state exactly what authority/evidence is missing.
   Do not widen scope merely to force a selection.
6. Explicit UNCERTAIN items and questions, if any.
7. Explicit non-scope and anti-drift notes.

NON-SCOPE / DO NOT DECIDE
-------------------------
Do not decide, redesign, or implement any of the following here:

- add_fk_helpers versus add_lookup_helpers public-surface consolidation;
- writable Lookup/enrichment semantics or projection conflict/merge policy;
- formula-mode certification or redesign;
- supported-type Cycle 3 work;
- package/module re-layout or shared-mechanism extraction;
- test-suite consolidation as a general exercise;
- new Trusted-Ingress architecture;
- Project Memory hygiene;
- 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
----------------------------
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 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_cycle2_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-cycle2-reentry-n1",
        f"r1@{BASELINE}",
        {"assess": phase},
    )


def _work_item() -> WorkItem:
    return WorkItem(
        1,
        WORK_ITEM_ID,
        (
            "Maintainer one-shot authorization on 2026-09-07 to begin the first "
            "bounded real N=1 DMC FK/reference-helper Cycle-2 assessment"
        ),
        "dmc-fk-cycle2-reentry-n1",
        "core",
        (ARTIFACT,),
        "assess",
        1,
        ("dmc", "fk-reference-helper", "cycle-2", "dogfood", "assessment"),
    )


def _policy() -> RepositoryPolicy:
    return RepositoryPolicy(
        1,
        "core-real-n1-dmc-dogfood",
        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}, 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}",
            "cycle1_closure_read_reference": f"git show {BASELINE}:{CYCLE1_CLOSURE_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(f"RUN ROOT: {STATE_ROOT / 'checkouts' / checkout_id}")
    print(f"SUMMARY: {summary_path}")
    print(f"RUN STATUS: {summary['run_status']}")
    print(f"HOP USED: {summary['hop_used']}/{summary['hop_limit']}")
    if summary["operator_error"]:
        print(f"OPERATOR ERROR: {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(f"WORKTREE CLEAN: {'YES' if summary['git_status_porcelain'] == '' else 'NO'}")

    return 0 if _success(summary) else 1


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