///|
/// Outcome of a pure Git worktree lifecycle `Inquiry`.
#derive(Eq, Debug)
pub(all) enum LifecycleOutcome {
  Succeeded(String)
  Refused(String)
}

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

///|
pub extend LifecycleOutcome with @debug.Debug::{to_repr}

///|
fn git_error_text(answer : ToolAnswer, action : String) -> String {
  match answer {
    Exited(code~, stdout~, stderr~) => {
      let detail = if !stderr.trim().is_empty() {
        stderr.trim().to_owned()
      } else if !stdout.trim().is_empty() {
        stdout.trim().to_owned()
      } else {
        "git exited with code \{code}"
      }
      "Could not \{action}: \{detail}"
    }
    NotInstalled => "Could not \{action}: git is not installed or not on PATH."
    TimedOut => "Could not \{action}: git timed out."
    Failed(reason) => "Could not \{action}: \{reason}"
  }
}

///|
fn has_control_or_whitespace(text : String) -> Bool {
  for ch in text {
    let code = ch.to_int()
    if code <= 0x20 || code == 0x7F {
      return true
    }
  }
  false
}

///|
fn parse_git_branch_name(raw : String) -> @app.LineName? {
  let trimmed = raw.trim().to_owned()
  guard !trimmed.is_empty() &&
    !trimmed.has_prefix("-") &&
    !trimmed.has_prefix("/") &&
    !trimmed.has_suffix("/") &&
    !trimmed.has_suffix(".") &&
    !trimmed.has_suffix(".lock") &&
    !trimmed.contains("..") &&
    !trimmed.contains("//") &&
    !trimmed.contains("@{") &&
    !trimmed.contains("~") &&
    !trimmed.contains("^") &&
    !trimmed.contains(":") &&
    !trimmed.contains("?") &&
    !trimmed.contains("*") &&
    !trimmed.contains("[") &&
    !trimmed.contains("\\") &&
    !has_control_or_whitespace(trimmed) else {
    return None
  }
  Some(@app.LineName::LineName(trimmed)) catch {
    _ => None
  }
}

///|
fn parse_git_rev_arg(raw : String) -> String? {
  let trimmed = raw.trim().to_owned()
  guard !trimmed.is_empty() &&
    !trimmed.has_prefix("-") &&
    !has_control_or_whitespace(trimmed) else {
    return None
  }
  Some(trimmed)
}

///|
/// Pure `Inquiry` creating a linked Git worktree at `target_path` on `branch`
/// (reusing an existing local branch if present, or creating a new branch from
/// `start_point` / HEAD).
pub fn git_create_worktree(
  store : FolderPath,
  target_path : String,
  branch : String,
  start_point~ : String? = None,
) -> Inquiry[LifecycleOutcome] {
  let clean_path = target_path.trim().to_owned()
  guard !clean_path.is_empty() else {
    return Done(Refused("Target worktree path must not be empty."))
  }
  guard !clean_path.has_prefix("-") else {
    return Done(
      Refused("Target worktree path must not start with '-': '\{clean_path}'."),
    )
  }
  guard parse_git_branch_name(branch) is Some(line) else {
    return Done(Refused("Invalid Git branch name '\{branch}'."))
  }
  let valid_start_point : String? = match start_point {
    None => None
    Some(sp) if sp.trim().is_empty() => None
    Some(sp) =>
      match parse_git_rev_arg(sp) {
        Some(v) => Some(v)
        None => return Done(Refused("Invalid Git start point '\{sp}'."))
      }
  }
  let branch_name = line.to_string()
  let check_call : ToolCall = {
    program: ToolName::git(),
    args: ["show-ref", "--verify", "--quiet", "refs/heads/\{branch_name}"],
    cwd: store,
  }
  Run(check_call, check_ans => {
    let branch_exists = match check_ans {
      Exited(code=0, ..) => true
      _ => false
    }
    let add_args : Array[String] = if branch_exists {
      ["worktree", "add", "--", clean_path, branch_name]
    } else {
      match valid_start_point {
        Some(sp) => ["worktree", "add", "-b", branch_name, "--", clean_path, sp]
        None => ["worktree", "add", "-b", branch_name, "--", clean_path]
      }
    }
    Run(
      {
        program: ToolName::git(),
        args: ReadOnlyArray::from_array(add_args),
        cwd: store,
      },
      ans => {
        match ans {
          Exited(code=0, ..) =>
            Done(
              Succeeded(
                "Created worktree at \{clean_path} on branch \{branch_name}.",
              ),
            )
          other => Done(Refused(git_error_text(other, "create worktree")))
        }
      },
    )
  })
}

///|
/// Pure `Inquiry` renaming the active branch of a Git workspace.
pub fn git_rename_worktree(
  ws_root : FolderPath,
  new_branch : String,
) -> Inquiry[LifecycleOutcome] {
  guard parse_git_branch_name(new_branch) is Some(line) else {
    return Done(Refused("Invalid Git branch name '\{new_branch}'."))
  }
  let name = line.to_string()
  Run(
    {
      program: ToolName::git(),
      args: ["branch", "-m", "--", name],
      cwd: ws_root,
    },
    ans => {
      match ans {
        Exited(code=0, ..) => Done(Succeeded("Renamed branch to \{name}."))
        other => Done(Refused(git_error_text(other, "rename branch")))
      }
    },
  )
}

///|
/// Pure `Inquiry` resetting a Git worktree to `target` (or `HEAD`), refusing
/// dirty worktrees unless `hard` is true.
pub fn git_reset_worktree(
  ws_root : FolderPath,
  target~ : String? = None,
  hard~ : Bool = false,
) -> Inquiry[LifecycleOutcome] {
  let reset_target = match target {
    Some(t) if !t.trim().is_empty() =>
      match parse_git_rev_arg(t) {
        Some(v) => v
        None => return Done(Refused("Invalid reset target '\{t}'."))
      }
    _ => "HEAD"
  }
  let do_reset = () => {
    Run(
      {
        program: ToolName::git(),
        args: ["reset", "--hard", reset_target, "--"],
        cwd: ws_root,
      },
      ans => {
        match ans {
          Exited(code=0, ..) =>
            Done(Succeeded("Reset workspace to \{reset_target}."))
          other => Done(Refused(git_error_text(other, "reset workspace")))
        }
      },
    )
  }
  if hard {
    return do_reset()
  }
  Run(
    { program: ToolName::git(), args: ["status", "--porcelain"], cwd: ws_root, },
    status_ans => {
      match status_ans {
        Exited(code=0, stdout~, ..) =>
          if !stdout.trim().is_empty() {
            Done(
              Refused(
                "Workspace has uncommitted changes; pass --hard to discard them and reset.",
              ),
            )
          } else {
            do_reset()
          }
        other =>
          Done(Refused(git_error_text(other, "inspect workspace status")))
      }
    },
  )
}

///|
/// Pure `Inquiry` removing a linked (non-default) Git worktree.
pub fn git_delete_worktree(
  store : FolderPath,
  ws_root : FolderPath,
  force~ : Bool = false,
) -> Inquiry[LifecycleOutcome] {
  let args : ReadOnlyArray[String] = if force {
    ["worktree", "remove", "--force", ws_root.to_string()]
  } else {
    ["worktree", "remove", ws_root.to_string()]
  }
  Run({ program: ToolName::git(), args, cwd: store, }, ans => {
    match ans {
      Exited(code=0, ..) =>
        Done(Succeeded("Removed worktree \{ws_root.to_string()}."))
      other => Done(Refused(git_error_text(other, "remove worktree")))
    }
  })
}