#!/usr/bin/env bash
# lane-add <git-url|path-to-existing-checkout> [name] [--local <path-you-already-have>] [--yes]
# Brings a repo under management at any time: clone (or copy an existing checkout's .git), register in
# registry/repos.yaml, create memory/<name>, and point the repo's Claude project memory at it.
# A local checkout with no origin remote is registered as local-only — no push/fetch/PR features
# until an origin is added with: git -C repos/<name> remote add origin <url>.

# Not to be confused with lane-with, which implements `lane with` (add a repo to a lane already
# started) — see scripts/README.md's naming note if these get mixed up again.
source "$(python3 -c 'import os,sys;print(os.path.dirname(os.path.realpath(sys.argv[1])))' "$0")/lib.sh"
source "$PRODUCT/scripts/gitstate.sh"
url="${1:-}"; [ -n "$url" ] || die "usage: lane-add <git-url|path-to-existing-checkout> [name]"
name="${2:-}"; [ "${name#--}" != "$name" ] && name=""; [ "$name" = -y ] && name=""
# --yes: in a workspace, link the mirror's Claude Code memory without asking (it is under ~/.claude, outside the workspace)
assume_yes=""; for a in "$@"; do case "$a" in --yes|-y) assume_yes=--yes ;; esac; done
from=""; for ((i=1;i<=$#;i++)); do [ "${!i}" = "--from" ] && j=$((i+1)) && from="${!j}"; done
given_local=""; for ((i=1;i<=$#;i++)); do [ "${!i}" = "--local" ] && j=$((i+1)) && given_local="${!j}"; done

# A local checkout works as the first argument. We take its origin as the remote and copy its git
# database rather than cloning again — and we remember where it came from, which is what lets
# `lane import` recognise the conversations you already had about it.
if [ -z "$from" ] && [ -d "$url" ] && { [ -d "$url/.git" ] || [ -f "$url/.git" ]; }; then
  from="$(cd "$url" && pwd)"
  origin="$(git -C "$from" remote get-url origin 2>/dev/null || true)"
  if [ -n "$origin" ]; then
    url="$origin"
    echo "using the checkout at $from (origin: $url)"
  else
    url=""
    echo "using the checkout at $from (no origin remote — registering as local-only: no push/fetch/PR features until one is added with: git -C repos/<name> remote add origin <url>)"
  fi
fi
if [ -n "$name" ]; then :
elif [ -n "$url" ]; then name=$(basename "$url" .git)
else name=$(basename "$from")
fi
local_path="${from:-$given_local}"
# Added from a url? Then ask, once, whether a checkout of it already exists on this machine.
# Answering is optional; it is how past conversations about the repo get recognised later.
if [ -z "$local_path" ] && [ -t 0 ] && [ -t 2 ]; then
  printf "  do you already have this cloned somewhere? path (blank to skip): " >&2
  read -r ans || true
  ans="${ans%$'\r'}"; ans="${ans/#\~/$HOME}"
  if [ -n "$ans" ]; then
    if [ -d "$ans/.git" ] || [ -f "$ans/.git" ]; then local_path="$(cd "$ans" && pwd)"
    else echo "  not a git checkout, ignoring: $ans" >&2; fi
  fi
fi

dst="$REPOS/$name"; [ -e "$dst" ] && die "$dst already exists"
if [ -n "$from" ]; then
  "$PRODUCT/scripts/copy-repo.sh" "$from" "$dst" || die "could not copy the checkout at $from"
else
  git clone -q "$url" "$dst" || { rm -rf "$dst"; die "could not clone $url"; }
  echo "cloned $url -> $dst"
fi
def=$(repo_default "$name")
python3 - "$REGISTRY/repos.yaml" "$name" "$url" "$def" "$local_path" <<'PY'
import sys; p,name,url,default,frm=sys.argv[1:]
t=open(p).read()
if f"\n  {name}:\n" in t: sys.exit(0)
origin_line = url if url else "(local-only)"
entry=f"""  {name}:
    path: repos/{name}
    origin: {origin_line}
    default_branch: {default}
    stack: []
    product: (fill in)
    status: active
    added: {__import__('datetime').date.today()}
""" + (f"    old_paths:\n      - {frm}\n" if frm else "")
open(p,"w").write(t.rstrip("\n")+"\n"+entry)
PY
# Record the checkout this repo came from, so `lane status` can report work happening out
# there instead of in a lane, and so the guard can refuse to read it. Three readers of
# registry/old-checkouts.json existed before this; nothing ever wrote it.
if [ -n "$local_path" ]; then
  python3 - "$REGISTRY/old-checkouts.json" "$local_path" <<'OLDCHK'
import json, os, subprocess, sys
path, src = sys.argv[1:]
def git(*a):
    try: return subprocess.check_output(["git", "-C", src, *a], text=True, stderr=subprocess.DEVNULL).strip()
    except Exception: return ""
try: d = json.load(open(path))
except Exception: d = {}
d[os.path.realpath(src)] = {"head": git("rev-parse", "HEAD"),
                            "dirty": len(git("status", "--porcelain").splitlines())}
json.dump(d, open(path, "w"), indent=2, sort_keys=True)
OLDCHK
  echo "  recorded $local_path as an old checkout — lane status flags work that happens there"
fi
mkdir -p "$MEMORY_DIR/$name"; [ -f "$MEMORY_DIR/$name/MEMORY.md" ] || printf '# Memory Index — %s\n' "$name" > "$MEMORY_DIR/$name/MEMORY.md"
if [ "$LANE_MODE" = workspace ]; then
  # anything under ~/.claude is shown and asked first (scripts/workspace.py), the same rule as lane init
  echo "registered $name (default $def); its memory is .repolane/memory/$name. Edit .repolane/registry/repos.yaml: stack/product."
  python3 -B "$PRODUCT/scripts/workspace.py" link-mirror "$AD" "$name" $assume_yes
else
slug=$(claude_project_dir "$dst"); proj="$HOME/.claude/projects/$slug"; mkdir -p "$proj"
if [ -d "$proj/memory" ] && [ ! -L "$proj/memory" ]; then cp -an "$proj/memory/." "$MEMORY_DIR/$name/" && rm -rf "$proj/memory"; fi
[ -L "$proj/memory" ] || ln -s "$MEMORY_DIR/$name" "$proj/memory"
echo "registered $name (default $def); memory -> memory/$name. Edit registry/repos.yaml: stack/product."
fi

# guard.py already denies a fixed set of secret-shaped filenames globally; every repo can also have
# its own (service-account.json, .npmrc, id_rsa, …) that set was never going to cover. Scan by
# filename only, never contents.
candidates=$("$PRODUCT/scripts/repo-secrets" "$name" scan 2>/dev/null || true)
if [ -n "$candidates" ]; then
  if [ -t 0 ] && [ -t 2 ]; then
    echo
    echo "  candidate secret/credential file(s) found in $name — most candidates in a typical repo turn out"
    echo "  to be ordinary source (password.py, token_store.py, ...), not actual secrets:"
    echo "$candidates" | sed 's/^/    /'
    printf "  deny future Read/Edit/Write of these files as secrets? [y/N]: " >&2
    read -r yn || true
    case "${yn:-n}" in
      [yY]*)
        # (not `mapfile`: macOS ships bash 3.2, which does not have it)
        cand_arr=()
        while IFS= read -r cand_line; do [ -z "$cand_line" ] || cand_arr+=("$cand_line"); done <<< "$candidates"
        "$PRODUCT/scripts/repo-secrets" "$name" add "${cand_arr[@]}"
        ;;
      *) echo "  skipped. To deny a real secret later: lane secrets $name add <path>...  To dismiss a false positive without denying it: lane secrets $name ignore <path>..." ;;
    esac
  else
    # No tty: this is the agent-driven path. Never deny silently — an AI agent driving `lane add`
    # must be told about candidates and must not have them denied without a human confirming,
    # the same principle behind every other guard behaviour in this repo. Most candidates turn out
    # to be ordinary source, not secrets, so this is a prompt to review, not an instruction to deny.
    n=$(echo "$candidates" | wc -l | tr -d ' ')
    echo
    echo "  $n candidate secret/credential file(s) found in $name — review them. Most turn out to be ordinary"
    echo "  source, not secrets. To deny reading a real secret: lane secrets $name add <path>...  (this makes"
    echo "  it unreadable to every future session). To dismiss a false positive without denying it:"
    echo "  lane secrets $name ignore <path>..."
    echo "$candidates" | sed 's/^/    /'
  fi
fi

# Past conversations live under the folder they ran in. If we know that folder, say what is there.
if [ -n "$local_path" ]; then
  oldslug=$(claude_project_dir "$local_path")
  olddir="${CLAUDE_HOME:-$HOME/.claude}/projects/$oldslug"
  n=0; [ -d "$olddir" ] && n=$(ls "$olddir"/*.jsonl 2>/dev/null | wc -l | tr -d ' ')
  if [ "$n" != 0 ]; then
    echo
    echo "  $n past conversation(s) about $name were found at $local_path"
    if [ -t 0 ] && [ -t 2 ]; then
      printf "  look at them now and turn them into a lane? [y/N]: " >&2
      read -r yn || true
      case "${yn:-n}" in [yY]*) exec "$PRODUCT/scripts/lane-import" ;; esac
    fi
    echo "  see them any time:  lane import --list"
  fi
fi
