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

SELF=$(readlink -f "${BASH_SOURCE[0]}")
SOURCE_ROOT=$(cd "$(dirname "$SELF")/.." && pwd -P)
SHIP_INIT=${LAND_ENROLL_SHIP_INIT:-"$SOURCE_ROOT/workflows/lib/ship-init.sh"}
GUARD_INSTALL=${LAND_ENROLL_GUARD_INSTALL:-"$SOURCE_ROOT/workflows/hooks/install-land-guard.sh"}

usage() { printf 'usage: land-enroll <repo-root> [--postlandcmd <command>]\n' >&2; exit 2; }

if [[ $# -eq 1 && ( "$1" == --help || "$1" == -h ) ]]; then
  usage
fi

die() { printf 'land-enroll: %s\n' "$1" >&2; exit "${2:-3}"; }

resolve_trunk() {
  local root=$1 trunk="" candidate
  trunk=$(git -C "$root" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##' || true)
  if [[ -z "$trunk" ]]; then
    for candidate in main master; do
      if git -C "$root" show-ref -q --verify "refs/heads/$candidate"; then
        [[ -z "$trunk" ]] || die "both main and master exist and origin/HEAD is unset"
        trunk=$candidate
      fi
    done
  fi
  [[ -n "$trunk" ]] || die "cannot resolve trunk branch"
  git -C "$root" check-ref-format "refs/heads/$trunk" >/dev/null || die "invalid trunk branch: $trunk"
  printf '%s' "$trunk"
}

[[ $# -ge 1 ]] || usage
ROOT=$1
shift
POSTLANDCMD=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --postlandcmd) [[ $# -ge 2 ]] || usage; POSTLANDCMD=$2; shift 2;;
    --help|-h) usage;;
    *) usage;;
  esac
done

ROOT=$(cd "$ROOT" 2>/dev/null && pwd -P) || die "repository root does not exist: $ROOT"
[[ -e "$ROOT/.git" ]] || die "not a Git repository: $ROOT"
[[ "$(git -C "$ROOT" rev-parse --show-toplevel)" == "$ROOT" ]] || die "path must be the repository root"
COMMON=$(git -C "$ROOT" rev-parse --git-common-dir)
[[ "$COMMON" == .git ]] || die "repository root must be the standalone checkout"
[[ -z "$(git -C "$ROOT" status --porcelain --untracked-files=all)" ]] || die "repository root is dirty"
ORIGIN=$(git -C "$ROOT" remote get-url origin 2>/dev/null || true)
[[ -n "$ORIGIN" ]] || die "origin remote is missing"
[[ -f "$SHIP_INIT" ]] || die "ship-init is unavailable: $SHIP_INIT"
[[ -f "$GUARD_INSTALL" ]] || die "land guard installer is unavailable: $GUARD_INSTALL"

TRUNK=$(resolve_trunk "$ROOT")
POLICY=""
if [[ -f "$ROOT/.land-policy" ]]; then
  POLICY=$(tr -d '[:space:]' < "$ROOT/.land-policy")
  [[ "$POLICY" == "pr" || "$POLICY" == "merge-to-main" ]] || die "unsupported .land-policy value: ${POLICY:-empty}"
fi

if PROPOSAL=$(bash "$SHIP_INIT" "$ROOT" 2>/dev/null); then
  die "ship-init Phase A unexpectedly succeeded"
else
  RC=$?
fi
[[ $RC -eq 10 ]] || die "ship-init Phase A failed: $PROPOSAL" "$RC"

read -r PROPOSAL_MODE PROPOSAL_BASE PROTECTED <<< "$(python3 -c '
import json, sys
p = json.load(sys.stdin)
print(p.get("proposed_mode", ""), p.get("base", ""), p.get("base_protected", ""))
' <<< "$PROPOSAL")"
[[ "$PROPOSAL_BASE" == "$TRUNK" ]] || die "ship-init base '$PROPOSAL_BASE' does not match resolved trunk '$TRUNK'"

MODE=$POLICY
if [[ -z "$MODE" ]]; then
  case "$PROPOSAL_MODE" in
    pr) MODE=pr;;
    merge-to-main)
      [[ "$PROTECTED" == "no" ]] || die "merge-to-main proposal lacks confirmed unprotected trunk; add .land-policy only after resolving repository policy"
      MODE=merge-to-main;;
    *) die "ambiguous proposed mode: ${PROPOSAL_MODE:-empty}";;
  esac
fi
[[ -z "$POSTLANDCMD" || "$MODE" == "merge-to-main" ]] || die "--postlandcmd requires merge-to-main mode"

WRAPPER="$ROOT/.claude/scripts/ship.sh"
FORCE=()
if [[ -e "$WRAPPER" ]]; then
  grep -qF 'GENERATED by ship-init.sh' "$WRAPPER" \
    || die "existing ship wrapper was not generated by ship-init; refusing to overwrite it"
  FORCE=(--force)
fi

PHASE_B=(bash "$SHIP_INIT" "$ROOT" --mode "$MODE" --base "$TRUNK" "${FORCE[@]}")
[[ -z "$POSTLANDCMD" ]] || PHASE_B+=(--postlandcmd "$POSTLANDCMD")
"${PHASE_B[@]}" >/dev/null
mkdir -p "$ROOT/.worktrees"
bash "$GUARD_INSTALL" "$ROOT" --trunk "$TRUNK" >/dev/null

QUEUE=disabled
if [[ "$MODE" == "merge-to-main" ]]; then
  git -C "$ROOT" config --local harness.landQueue stage-a
  QUEUE=stage-a
else
  if git -C "$ROOT" config --local --get-all harness.landQueue >/dev/null 2>&1; then
    git -C "$ROOT" config --local --unset-all harness.landQueue
  fi
fi

bash "$ROOT/.claude/scripts/test-ship.sh" >/dev/null
printf '{"status":"enrolled","root":"%s","mode":"%s","trunk":"%s","queue":"%s"}\n' "$ROOT" "$MODE" "$TRUNK" "$QUEUE"
