#!/usr/bin/env bash
set -euo pipefail

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  cat <<'EOF'
Usage: .agent/scripts/devloop-start [--bead ID] [--meta|--focus MODE] <slice-title>

Start one devloop slice, append an operating-log entry, update ACTIVE-LOOP.md,
and refresh generated conductor state. Use --meta, or --focus Meta, for process
and scaffold work. Obvious process/convention titles infer Meta automatically.

When --bead is supplied and bd is available, claim that issue and record its id
in ACTIVE-LOOP.md so review/handoff can connect the current slice to the durable
backlog.
EOF
  exit 0
fi

start_focus="Direction"
slice_bead=""
while [ "$#" -gt 0 ]; do
  case "${1:-}" in
    --bead)
      slice_bead="${2:?usage: devloop-start --bead ID <slice-title>}"
      shift 2
      ;;
    --meta)
      start_focus="Meta"
      shift
      ;;
    --focus)
      start_focus="${2:?usage: devloop-start --focus MODE <slice-title>}"
      shift 2
      ;;
    --)
      shift
      break
      ;;
    -*)
      printf 'unknown option: %s\n' "$1" >&2
      exit 2
      ;;
    *)
      break
      ;;
  esac
done

case "$start_focus" in
  Direction|Evidence|Construction|Proof|Artifact|Velocity|Meta) ;;
  *)
    printf 'invalid focus mode: %s\n' "$start_focus" >&2
    exit 2
    ;;
esac

title="${1:?usage: devloop-start [--bead ID] [--meta|--focus MODE] <slice-title>}"
# Meta inference covers process titles such as meta, process, scaffold,
# devloop, conductor, and convention slices.
case "$start_focus:$title" in
  Direction:[Mm]eta*|Direction:[Pp]rocess*|Direction:[Ss]caffold*)
    start_focus="Meta"
    ;;
  Direction:[Dd]evloop*|Direction:[Cc]onductor*|Direction:*[Cc]onvention*)
    start_focus="Meta"
    ;;
esac
repo="${POLYLOGUE_REPO:-$(git rev-parse --show-toplevel 2>/dev/null || printf /realm/project/polylogue)}"
root="${POLYLOGUE_AGENT_LOG_ROOT:-$repo/.agent/conductor-devloop}"
next_focus="Evidence"
next_decision="gather current evidence before editing"
meta_origin="no"
if [ "$start_focus" = "Meta" ]; then
  next_focus="Meta"
  next_decision="audit process evidence and choose the smallest executable scaffold improvement"
  meta_origin="yes"
fi

bead_log="Bead: none"
if [ -n "$slice_bead" ]; then
  bead_log="Bead: $slice_bead"
  if command -v bd >/dev/null 2>&1; then
    bd update "$slice_bead" --claim --json >/dev/null
    if [ -d "$repo/.beads" ]; then
      bd export --output "$repo/.beads/issues.jsonl" >/dev/null
    fi
  else
    printf 'WARN: bd is not available; recorded bead id but did not claim %s\n' "$slice_bead" >&2
  fi
fi

"$(dirname "$0")/devloop-log" "$title" "$bead_log
Focus: $start_focus -> $next_focus
Trigger: $title
Primary aim: define the slice against current evidence before editing.
Evidence touched: initial devloop status, review, active loop, and slice trigger.
Action taken: started the slice and moved focus to $next_focus.
Artifact/proof: pending; record the narrow proof before claiming completion.
Velocity note: slice started through devloop-start so elapsed time is tracked.
Next decision: $next_decision."

if [ -f "$root/ACTIVE-LOOP.md" ]; then
  python3 - "$root/ACTIVE-LOOP.md" "$title" "$start_focus" "$next_focus" "$next_decision" "$meta_origin" "$slice_bead" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
title = sys.argv[2]
start_focus = sys.argv[3]
next_focus = sys.argv[4]
next_decision = sys.argv[5]
meta_origin = sys.argv[6]
slice_bead = sys.argv[7]
text = path.read_text()
slice_body = title if not slice_bead else f"{title}\n\nBead: {slice_bead}"
replacements = {
    "Current Slice": f"Current Slice\n\n{slice_body}",
    "Meta Origin": f"Meta Origin\n\n{meta_origin}",
    "Current Focus": (
        f"Current Focus\n\nFocus: {start_focus} -> {next_focus}\n\n"
        f"Trigger: {title}\n\n"
        f"Decision: {next_decision.capitalize()}, then record the next material focus switch."
    ),
    "Accepted Warnings": (
        "Accepted Warnings\n\n"
        "None recorded for this slice. If `devloop-review` warnings are consciously accepted, "
        "record only current-slice exceptions here; historical proofs and completed slices belong "
        "in `OPERATING-LOG.md` or `DEMO-RADAR.md`."
    ),
    "Next Action": f"Next Action\n\nContinue in `{next_focus}` mode: {next_decision}.",
    "Do Not Drift": (
        "Do Not Drift\n\n"
        "- Do not reintroduce `/realm/tmp/polylogue-dev/archive` as a live database root.\n"
        "- Do not quote counts without archive root and schema version.\n"
        "- Do not preserve compatibility endpoints, flags, or DTOs just because removal\n"
        "  is broader than the current file.\n"
        "- Stay on the current long-lived branch for ordinary loop work; commit logical,\n"
        "  proven chunks by path and avoid worktrees unless isolation is actually needed.\n"
        "- Use compile/test/daemon wait time for ahead work in this checkout. A failed\n"
        "  proof can be retried after batched fixes; it should not freeze the loop.\n"
        "- Do not overcorrect into \"demo instead of substrate.\" Demonstrated value is the\n"
        "  forcing function, but substrate repair is the right slice whenever broken\n"
        "  archive/query/rendering state would make a demo false or fragile.\n"
        "- Add slice-specific guardrails deliberately; do not inherit stale guardrails\n"
        "  from the previous slice."
    ),
}
for heading, body in replacements.items():
    marker = f"## {heading.splitlines()[0]}"
    start = text.find(marker)
    if start == -1:
        continue
    next_start = text.find("\n## ", start + 1)
    if next_start == -1:
        next_start = len(text)
    text = text[:start] + "## " + body + "\n" + text[next_start:]
if "## Meta Origin" not in text:
    marker = "## Current Focus"
    start = text.find(marker)
    if start != -1:
        text = text[:start] + f"## Meta Origin\n\n{meta_origin}\n\n" + text[start:]
path.write_text(text)
PY
fi

POLYLOGUE_CONDUCTOR_PACKET="$root" "$(dirname "$0")/devloop-sync" >/dev/null
