///| AGENTS.md / CLAUDE.md generation for the Home Repo.

///|
pub let agents_block_begin : String = ""

///|
pub let agents_block_end : String = ""

///|
/// The managed "Other Repos" section, between `agents_block_begin` and
/// `agents_block_end`. Each line is a navigation pointer an agent can act
/// on: where the clone lives, where to clone it from, and what part of it
/// is checked out.
pub fn render_agents_block(manifest : HomeManifest) -> String {
  let sb = StringBuilder()
  sb.write_string(agents_block_begin)
  sb.write_string("\n")
  sb.write_string(
    "\n",
  )
  sb.write_string("## Other Repos\n\n")
  if manifest.repos.length() == 0 {
    sb.write_string(
      "No repositories yet. Add one with `bit home add  --path `.\n",
    )
  } else {
    sb.write_string(
      "Each repository keeps its own history, remote and AGENTS.md. Run `bit home sync` to clone missing ones and fast-forward the rest, `bit home status` for an overview, and `bit home wt add  ` for a per-feature worktree.\n\n",
    )
    for repo in manifest.repos {
      sb.write_string("- **\{repo.name}**")
      if repo.description is Some(d) {
        sb.write_string(" (\{d})")
      }
      sb.write_string(": `\{repo.path}`.")
      if repo.url is Some(u) {
        sb.write_string(" Clone from `\{u}` if missing.")
      }
      if repo.branch is Some(b) {
        sb.write_string(" Branch `\{b}`.")
      }
      if repo.subdir is Some(s) {
        sb.write_string(" Only `\{s}/` is checked out (sparse).")
      }
      if repo.notes is Some(n) {
        sb.write_string(" \{n}")
      }
      sb.write_string("\n")
    }
  }
  sb.write_string(agents_block_end)
  sb.write_string("\n")
  sb.to_string()
}

///|
/// Initial AGENTS.md for a new Home Repo.
pub fn agents_md_template(manifest : HomeManifest) -> String {
  "# Home Repo\n\n" +
  "Start agent sessions here. This repository holds the shared skills, steering files and docs; the code lives in the repositories listed below.\n\n" +
  render_agents_block(manifest)
}

///|
/// CLAUDE.md for harnesses that load CLAUDE.md instead of AGENTS.md:
/// Claude Code expands `@AGENTS.md` into the file's contents.
pub let claude_md_pointer : String = "@AGENTS.md\n"

///|
/// Replace the managed block in `existing` (or append it when absent).
/// Text outside the markers is kept byte for byte.
pub fn update_agents_md(existing : String, block : String) -> String {
  match (existing.find(agents_block_begin), existing.find(agents_block_end)) {
    (Some(b), Some(e)) if e > b => {
      let after_start = e + agents_block_end.length()
      // Swallow the newline that followed the old end marker; `block` ends
      // with its own.
      let after = if after_start < existing.length() &&
        existing.unsafe_get(after_start) == '\n' {
        after_start + 1
      } else {
        after_start
      }
      String::unsafe_substring(existing, start=0, end=b) +
      block +
      String::unsafe_substring(existing, start=after, end=existing.length())
    }
    _ => {
      let sep = if existing.length() == 0 {
        ""
      } else if existing.has_suffix("\n\n") {
        ""
      } else if existing.has_suffix("\n") {
        "\n"
      } else {
        "\n\n"
      }
      existing + sep + block
    }
  }
}

///|
/// Per-feature worktrees live inside the repository's clone, under this
/// directory (excluded via `.git/info/exclude`).
pub let worktrees_dir_name : String = ".worktrees"

///|
/// A feature name doubles as the worktree directory and the branch name:
/// letters, digits, `.`, `_`, `-` and `/`; no empty, `.` or `..`
/// component; not starting with `-`; not ending in `.lock`.
pub fn is_valid_feature_name(feature : String) -> Bool {
  if feature.length() == 0 ||
    feature.has_prefix("-") ||
    feature.has_prefix("/") ||
    feature.has_suffix("/") ||
    feature.has_suffix(".lock") {
    return false
  }
  for c in feature {
    if !(
        (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z') ||
        (c >= '0' && c <= '9') ||
        c == '.' ||
        c == '_' ||
        c == '-' ||
        c == '/'
      ) {
      return false
    }
  }
  for part in feature.split("/") {
    let p = part.to_owned()
    if p.length() == 0 || p == "." || p == ".." || p.has_prefix(".") {
      return false
    }
  }
  true
}

///|
pub fn worktree_path(repo_abs : String, feature : String) -> String {
  repo_abs + "/" + worktrees_dir_name + "/" + feature
}

///|
/// Branch / dirty summary of one repository. `branch` and `changes` come
/// from `status --porcelain --branch`; `upstream`, `ahead` and `behind` are
/// filled in separately (see `upstream_from_config`).
pub(all) struct RepoStatus {
  branch : String?
  upstream : String?
  ahead : Int
  behind : Int
  changes : Int
} derive(Debug, Eq)

///|
pub extend RepoStatus with Debug::{to_repr}

///|
pub extend RepoStatus with Eq::{not_equal, equal}

///|
/// Parse `status --porcelain --branch` (v1): the `## ` header gives the
/// branch (`None` when detached), every other line is one change.
pub fn parse_porcelain_status(output : String) -> RepoStatus {
  let mut branch : String? = None
  let mut changes = 0
  for line_view in output.split("\n") {
    let line = line_view.to_owned()
    if line.length() == 0 {
      continue
    }
    if line.has_prefix("## ") {
      let head = String::unsafe_substring(line, start=3, end=line.length())
      let head = if head.has_prefix("No commits yet on ") {
        String::unsafe_substring(head, start=18, end=head.length())
      } else if head.has_prefix("Initial commit on ") {
        String::unsafe_substring(head, start=18, end=head.length())
      } else {
        head
      }
      let name = match head.find("...") {
        Some(i) => String::unsafe_substring(head, start=0, end=i)
        None =>
          match head.find(" ") {
            Some(i) => String::unsafe_substring(head, start=0, end=i)
            None => head
          }
      }
      branch = if name == "HEAD" || name.length() == 0 { None } else { Some(name) }
    } else {
      changes += 1
    }
  }
  { branch, upstream: None, ahead: 0, behind: 0, changes }
}

///|
/// The upstream of a branch from its `branch..remote` / `.merge`
/// config: `(display name, ref to compare against)`, e.g.
/// `("origin/main", "refs/remotes/origin/main")`.
pub fn upstream_from_config(remote : String, merge : String) -> (String, String)? {
  let remote = remote.trim(chars=" \t\r\n").to_owned()
  let merge = merge.trim(chars=" \t\r\n").to_owned()
  if remote.length() == 0 || !merge.has_prefix("refs/heads/") {
    return None
  }
  let short = String::unsafe_substring(merge, start=11, end=merge.length())
  if remote == "." {
    Some((short, merge))
  } else {
    Some((remote + "/" + short, "refs/remotes/" + remote + "/" + short))
  }
}

///|
/// One-line human summary used by `bit home status`.
pub fn describe_status(status : RepoStatus) -> String {
  let parts : Array[String] = []
  parts.push(
    match status.branch {
      Some(b) => b
      None => "(detached)"
    },
  )
  match status.upstream {
    Some(u) =>
      if status.ahead == 0 && status.behind == 0 {
        parts.push("up to date with \{u}")
      } else {
        let ab : Array[String] = []
        if status.ahead > 0 {
          ab.push("ahead \{status.ahead}")
        }
        if status.behind > 0 {
          ab.push("behind \{status.behind}")
        }
        parts.push(ab.join(", ") + " vs \{u}")
      }
    None => parts.push("no upstream")
  }
  parts.push(
    if status.changes == 0 {
      "clean"
    } else {
      "\{status.changes} changed"
    },
  )
  parts.join(", ")
}