#!/usr/bin/env bash
# Regression harness for host-specific Gitea tea login resolution.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/gitea-login-resolution}"
REPO_DIR="$WORK_DIR/repo"
BIN_DIR="$WORK_DIR/bin"
LOG_FILE="$WORK_DIR/calls.log"
CREDENTIALS_FILE="$WORK_DIR/credentials.json"

rm -rf "$WORK_DIR"
mkdir -p "$REPO_DIR" "$BIN_DIR"

git -C "$REPO_DIR" init -q
git -C "$REPO_DIR" remote add origin https://git.uscllc.com/USC/uconnect.git

cat > "$CREDENTIALS_FILE" <<'JSON'
{
  "gitea": {
    "mosaicstack": {
      "url": "https://git.mosaicstack.dev",
      "token": "mosaic-token"
    },
    "usc": {
      "url": "https://git.uscllc.com",
      "token": "usc-token"
    }
  }
}
JSON

cat > "$BIN_DIR/tea" <<'SH'
#!/usr/bin/env bash
set -euo pipefail

if [[ "$*" == "login list --output json" ]]; then
    cat <<'JSON'
[
  {"name":"evil-usc","url":"https://evilgit.uscllc.com","user":"bad.actor"},
  {"name":"usc","url":"https://git.uscllc.com","user":"ci-bot"}
]
JSON
    exit 0
fi

if [[ "${1:-}" == "api" ]]; then
    printf '%s\n' '{"login":"ci-bot"}'
    exit 0
fi

printf 'tea %s\n' "$*" >> "$MOSAIC_TEST_LOG"
if [[ "${MOSAIC_TEA_FAIL_PR_CREATE:-}" == "1" && "$*" == pr\ create* ]]; then
    echo 'GetUserByName: simulated stale login failure' >&2
    exit 1
fi
exit 0
SH

cat > "$BIN_DIR/curl" <<'SH'
#!/usr/bin/env bash
set -euo pipefail

printf 'curl %s\n' "$*" >> "$MOSAIC_TEST_LOG"
url="${*: -1}"
case "$url" in
    */pulls/*.diff)
        printf 'diff --git a/file b/file\n'
        ;;
    */pulls/*)
        printf '{"head":{"sha":"abc123"}}'
        ;;
    */commits/*/status)
        printf '{"state":"success","statuses":[{"context":"ci/mock","status":"success"}]}'
        ;;
    *)
        printf '{}'
        ;;
esac
SH

chmod +x "$BIN_DIR/tea" "$BIN_DIR/curl"

run_in_repo() {
    (
        cd "$REPO_DIR"
        PATH="$BIN_DIR:$PATH" \
        MOSAIC_CREDENTIALS_FILE="$CREDENTIALS_FILE" \
        MOSAIC_TEST_LOG="$LOG_FILE" \
        "$@"
    )
}

usc_login=$(run_in_repo bash -c '
    export GITEA_LOGIN=mosaicstack
    export GITEA_URL=https://git.mosaicstack.dev
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_gitea_login
')
if [[ "$usc_login" != "usc" ]]; then
    echo "Expected USC host to resolve tea login 'usc' despite stale mosaicstack env; got '$usc_login'" >&2
    exit 1
fi

usc_login_with_usc_url=$(run_in_repo bash -c '
    export GITEA_LOGIN=mosaicstack
    export GITEA_URL=https://git.uscllc.com
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_gitea_login
')
if [[ "$usc_login_with_usc_url" != "usc" ]]; then
    echo "Expected USC host to reject stale GITEA_LOGIN even when GITEA_URL matches USC; got '$usc_login_with_usc_url'" >&2
    exit 1
fi

usc_login_without_url=$(run_in_repo bash -c '
    export GITEA_LOGIN=mosaicstack
    unset GITEA_URL
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_gitea_login
')
if [[ "$usc_login_without_url" != "usc" ]]; then
    echo "Expected USC host to ignore unmatched GITEA_LOGIN without URL; got '$usc_login_without_url'" >&2
    exit 1
fi

git -C "$REPO_DIR" remote set-url origin https://hermes:token@git.uscllc.com/USC/uconnect.git
embedded_host=$(run_in_repo bash -c '
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_remote_host
')
if [[ "$embedded_host" != "git.uscllc.com" ]]; then
    echo "Expected credential-bearing remote host to strip userinfo; got '$embedded_host'" >&2
    exit 1
fi
git -C "$REPO_DIR" remote set-url origin https://git.uscllc.com/USC/uconnect.git

override_login=$(run_in_repo bash -c '
    export GITEA_LOGIN=usc
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_gitea_login_for_repo_override
')
if [[ "$override_login" != "usc" ]]; then
    echo "Expected --repo override path to honor explicit GITEA_LOGIN; got '$override_login'" >&2
    exit 1
fi

git -C "$REPO_DIR" remote set-url origin https://git.mosaicstack.dev/mosaicstack/stack.git
: > "$LOG_FILE"
run_in_repo env GITEA_LOGIN=usc "$SCRIPT_DIR/issue-list.sh" --repo USC/uconnect -n 1
grep -q -- 'tea issues list --repo USC/uconnect --login usc' "$LOG_FILE"
git -C "$REPO_DIR" remote set-url origin https://git.uscllc.com/USC/uconnect.git

: > "$LOG_FILE"
run_in_repo "$SCRIPT_DIR/issue-close.sh" -i 42
grep -q -- 'tea issue close 42 --repo USC/uconnect --login usc' "$LOG_FILE"
if grep -q -- '--login mosaicstack' "$LOG_FILE"; then
    echo "issue-close.sh used hardcoded mosaicstack login on USC host" >&2
    exit 1
fi

: > "$LOG_FILE"
run_in_repo "$SCRIPT_DIR/milestone-list.sh"
grep -q -- 'tea milestone list --repo USC/uconnect --login usc' "$LOG_FILE"

: > "$LOG_FILE"
run_in_repo "$SCRIPT_DIR/milestone-create.sh" -t "0.2.0" -d "USC milestone"
grep -q -- 'tea milestones create --title 0.2.0 --description USC milestone --repo USC/uconnect --login usc' "$LOG_FILE"

: > "$LOG_FILE"
run_in_repo "$SCRIPT_DIR/milestone-close.sh" -t "0.2.0"
grep -q -- 'tea milestone close 0.2.0 --repo USC/uconnect --login usc' "$LOG_FILE"

if command -v pwsh >/dev/null 2>&1; then
    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/issue-list.ps1" -Limit 1
    grep -q -- 'tea issues list --state open --limit 1 --repo USC/uconnect --login usc' "$LOG_FILE"

    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/issue-create.ps1" -Title "PowerShell issue"
    grep -q -- 'tea issue create --title PowerShell issue --repo USC/uconnect --login usc' "$LOG_FILE"

    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/pr-list.ps1" -Limit 1
    grep -q -- 'tea pr list --state open --limit 1 --repo USC/uconnect --login usc' "$LOG_FILE"

    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/pr-create.ps1" -Title "PowerShell PR"
    grep -q -- 'tea pr create --title PowerShell PR --head master --repo USC/uconnect --login usc' "$LOG_FILE"

    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/pr-merge.ps1" -Number 42 -SkipQueueGuard
    grep -q -- 'tea pr merge 42 --style squash --repo USC/uconnect --login usc' "$LOG_FILE"

    : > "$LOG_FILE"
    run_in_repo pwsh -NoProfile -File "$SCRIPT_DIR/milestone-create.ps1" -List
    grep -q -- 'tea milestones list --repo USC/uconnect --login usc' "$LOG_FILE"
fi

: > "$LOG_FILE"
if run_in_repo "$SCRIPT_DIR/pr-diff.sh" --repo USC/uconnect -n 7 >/dev/null 2>&1; then
    echo "Expected pr-diff.sh --repo without host to fail loud" >&2
    exit 1
fi
if grep -q -- 'git.mosaicstack.dev/api/v1/repos/USC/uconnect' "$LOG_FILE"; then
    echo "pr-diff.sh --repo defaulted API host to git.mosaicstack.dev" >&2
    exit 1
fi

: > "$LOG_FILE"
run_in_repo env GITEA_URL=https://git.uscllc.com "$SCRIPT_DIR/pr-diff.sh" --repo USC/uconnect -n 7 >/dev/null
grep -q -- 'curl .*https://git.uscllc.com/api/v1/repos/USC/uconnect/pulls/7.diff' "$LOG_FILE"

: > "$LOG_FILE"
run_in_repo "$SCRIPT_DIR/pr-ci-wait.sh" --repo USC/uconnect --host git.uscllc.com -n 9 -t 2 -i 1
grep -q -- 'curl .*https://git.uscllc.com/api/v1/repos/USC/uconnect/pulls/9' "$LOG_FILE"
grep -q -- 'curl .*https://git.uscllc.com/api/v1/repos/USC/uconnect/commits/abc123/status' "$LOG_FILE"

: > "$LOG_FILE"
run_in_repo env MOSAIC_TEA_FAIL_PR_CREATE=1 GITEA_TOKEN=usc-token GITEA_URL=https://git.uscllc.com "$SCRIPT_DIR/pr-create.sh" -t "USC API fallback" -H feature/pr-create
grep -q -- 'tea pr create --repo USC/uconnect --login usc --title USC API fallback --head feature/pr-create' "$LOG_FILE"
grep -q -- 'curl .*Authorization: token usc-token .*https://git.uscllc.com/api/v1/repos/USC/uconnect/pulls' "$LOG_FILE"
if grep -q -- 'git.mosaicstack.dev/api/v1/repos/USC/uconnect/pulls' "$LOG_FILE"; then
    echo "pr-create.sh API fallback defaulted USC repo to git.mosaicstack.dev" >&2
    exit 1
fi

git -C "$REPO_DIR" remote set-url origin https://git.mosaicstack.dev/mosaicstack/stack.git
: > "$LOG_FILE"
run_in_repo env GITEA_TOKEN=mosaic-token GITEA_URL=https://git.mosaicstack.dev "$SCRIPT_DIR/issue-close.sh" -i 536
grep -q -- 'curl .*https://git.mosaicstack.dev/api/v1/repos/mosaicstack/stack/issues/536' "$LOG_FILE"
if grep -q -- 'tea issue close 536 .*--login mosaicstack' "$LOG_FILE"; then
    echo "issue-close.sh invented a mosaicstack tea login instead of using API fallback" >&2
    exit 1
fi

# ---------------------------------------------------------------------------
# #560: loud diagnostic + host-derived login for BOTH instances + override-wins
# ---------------------------------------------------------------------------

# Loud diagnostic: a host with no matching tea login must emit an actionable
# error to stderr (the previous behavior was a SILENT failure). The original
# mock defines only usc/evil-usc logins, so mosaicstack resolution fails here.
git -C "$REPO_DIR" remote set-url origin https://git.mosaicstack.dev/mosaicstack/stack.git
diag_stderr=$(run_in_repo bash -c '
    source "'"$SCRIPT_DIR"'/detect-platform.sh"
    get_gitea_login_for_host git.mosaicstack.dev
' 2>&1 1>/dev/null || true)
if ! grep -q "no Gitea tea login matches host 'git.mosaicstack.dev'" <<<"$diag_stderr"; then
    echo "Expected loud diagnostic naming the unresolved host; got: $diag_stderr" >&2
    exit 1
fi
if ! grep -q "Available tea logins:" <<<"$diag_stderr"; then
    echo "Expected diagnostic to list available tea logins; got: $diag_stderr" >&2
    exit 1
fi

# Both-instance host derivation + override-wins, using a mock that DOES define a
# mosaicstack login. Scoped to this section so the API-fallback assertions above
# (which rely on mosaicstack having NO tea login) remain valid.
BIN_DIR2="$WORK_DIR/bin2"
mkdir -p "$BIN_DIR2"
cp "$BIN_DIR/curl" "$BIN_DIR2/curl"
cat > "$BIN_DIR2/tea" <<'SH'
#!/usr/bin/env bash
set -euo pipefail
if [[ "$*" == "login list --output json" ]]; then
    cat <<'JSON'
[
  {"name":"mosaicstack","url":"https://git.mosaicstack.dev","user":"ci-bot"},
  {"name":"usc","url":"https://git.uscllc.com","user":"ci-bot"}
]
JSON
    exit 0
fi
printf 'tea %s\n' "$*" >> "$MOSAIC_TEST_LOG"
exit 0
SH
chmod +x "$BIN_DIR2/tea"

run_in_repo2() {
    (
        cd "$REPO_DIR"
        PATH="$BIN_DIR2:$PATH" \
        MOSAIC_CREDENTIALS_FILE="$CREDENTIALS_FILE" \
        MOSAIC_TEST_LOG="$LOG_FILE" \
        "$@"
    )
}

git -C "$REPO_DIR" remote set-url origin https://git.mosaicstack.dev/mosaicstack/stack.git
mosaic_login=$(run_in_repo2 bash -c 'source "'"$SCRIPT_DIR"'/detect-platform.sh"; get_gitea_login')
if [[ "$mosaic_login" != "mosaicstack" ]]; then
    echo "Expected mosaicstack origin to derive login 'mosaicstack'; got '$mosaic_login'" >&2
    exit 1
fi

git -C "$REPO_DIR" remote set-url origin https://git.uscllc.com/USC/uconnect.git
usc_login_derived=$(run_in_repo2 bash -c 'source "'"$SCRIPT_DIR"'/detect-platform.sh"; get_gitea_login')
if [[ "$usc_login_derived" != "usc" ]]; then
    echo "Expected usc origin to derive login 'usc'; got '$usc_login_derived'" >&2
    exit 1
fi

# Explicit GITEA_LOGIN override is honored when it matches the host.
git -C "$REPO_DIR" remote set-url origin https://git.mosaicstack.dev/mosaicstack/stack.git
override_wins=$(run_in_repo2 bash -c 'export GITEA_LOGIN=mosaicstack; source "'"$SCRIPT_DIR"'/detect-platform.sh"; get_gitea_login')
if [[ "$override_wins" != "mosaicstack" ]]; then
    echo "Expected valid GITEA_LOGIN override to win on mosaicstack host; got '$override_wins'" >&2
    exit 1
fi
git -C "$REPO_DIR" remote set-url origin https://git.uscllc.com/USC/uconnect.git

echo "Gitea login resolution regression harness passed"
