#!/usr/bin/env bash

# Gate 1 TypeScript static analysis — the single place that decides HOW a project
# is type-checked (#436).
#
# NOT incremental (deliberately, #534): TypeScript type-checking cannot be
# reduced to "staged files only". `tsc` has no single-file check mode — it must
# resolve the whole module graph to report a file's real type errors, so
# type-checking only the changed files would silently miss "changing B.ts breaks
# an unchanged caller in A.ts". Pre-commit therefore runs the project's full
# typecheck (`npm run typecheck` / `npx tsc --noEmit`) every commit. This is the
# CORRECTNESS-preserving exception to xp-gate's incremental rule: lint (ESLint /
# Biome) IS incremental (staged files / --staged), but type-check stays full
# because incremental type-checking would be wrong, not just slower.
#
# Before this file, `githooks/pre-commit` and `githooks/adapters/typescript.sh` each
# hardcoded `npx tsc --noEmit`. Plain tsc cannot resolve `.vue` single-file
# components, so every `import X from './Foo.vue'` became a TS2307 and a Vue project
# whose own `vue-tsc --noEmit` run is clean was blocked on every commit. Because
# pre-commit runs under `set -o pipefail`, those false findings really did block.
#
# Resolution order:
#   1. GATE_TS_TYPECHECK_CMD        explicit override, same precedent as SKIP_VERSION_CHECK
#   2. package.json scripts.typecheck
#   3. package.json scripts.type-check (the name create-vue generates)
#   4. `npx tsc --noEmit --skipLibCheck` — the pre-#436 behavior, unchanged
#
# Return codes follow the gate exit-code contract: 0 clean, 1 findings, 2 checker
# unavailable (a tool failure must never be read as "no type errors").

resolve_typecheck_command() {
  if [ -n "${GATE_TS_TYPECHECK_CMD:-}" ]; then
    printf '%s' "$GATE_TS_TYPECHECK_CMD"
    return 0
  fi

  [ -f "package.json" ] || return 1
  command -v node >/dev/null 2>&1 || return 1

  local declared_script
  declared_script=$(node -e '
    let pkg;
    try {
      pkg = JSON.parse(require("fs").readFileSync("package.json", "utf8"));
    } catch {
      process.exit(0);
    }
    const scripts = (pkg && pkg.scripts) || {};
    if (scripts.typecheck) process.stdout.write("typecheck");
    else if (scripts["type-check"]) process.stdout.write("type-check");
  ' 2>/dev/null) || return 1

  [ -n "$declared_script" ] || return 1

  printf 'npm run %s' "$declared_script"
  return 0
}

# Runs tsc, preferring the locally installed compiler over npx.
#
# `npx tsc --version` measured 1941 ms here against 234 ms for
# `node node_modules/typescript/bin/tsc --version` -- identical output, 1.7 s of
# package resolution in between. typecheck.sh called `npx tsc` at five sites and
# a single commit reaches several of them, so the whole typecheck half of Gate 1
# paid that toll repeatedly. pre-commit:4324-4345 already made exactly this
# change for archlint ("measured: 1909 ms via npx vs 319 ms direct"); typecheck
# never got it.
#
# npx stays as the fallback so a consumer repo with no local install behaves
# exactly as before. Nothing is cached: resolving a path is a couple of `test -f`
# calls, and a cache would have to be invalidated whenever node_modules changes.
_tsc_command() {
  if [ -f "node_modules/typescript/bin/tsc" ] && command -v node >/dev/null 2>&1; then
    node "node_modules/typescript/bin/tsc" "$@"
    return $?
  fi
  # The fallback stays a real `npx` call. Rewording this line into a recursive
  # _tsc_command call is a stack overflow, not a fallback.
  npx tsc "$@"
}

# The #293 extra pass: projects commonly exclude test files from tsconfig.json, so
# their type errors accumulate silently. Only meaningful for the tsc fallback —
# a project checker covers the files its own config declares.
run_test_file_pass() {
  local has_tests_in_tsc=false
  if _tsc_command --noEmit --skipLibCheck --listFiles 2>/dev/null | grep -qE '__tests__/|\.test\.ts|\.spec\.ts'; then
    has_tests_in_tsc=true
  fi
  [ "$has_tests_in_tsc" = false ] || return 0

  local test_pass_exit=0
  if [ -f "tsconfig.tests.json" ]; then
    echo "Checking test files with tsconfig.tests.json..."
    _tsc_command --noEmit --project tsconfig.tests.json 2>&1 | head -30
    test_pass_exit=${PIPESTATUS[0]}
  else
    echo "Checking test files for type errors..."
    local temp_tsconfig=".tsconfig.withtests.json"
    # `exclude` and `include` do NOT accept the same globs. TypeScript allows a
    # trailing `**` in `exclude` but rejects it in `include` with TS5010
    # ("File specification cannot end in a recursive directory wildcard").
    #
    # This block used to push `src/**/__tests__/**` -- copied from the exclude
    # list, where it is legal and common -- into `include`. The generated config
    # was therefore ALWAYS invalid, and tsc aborted before checking a single
    # file. Every commit in a project with the standard
    #
    #     "exclude": ["src/**/__tests__/**", ...]
    #
    # was blocked with "❌ TYPE ERRORS in test files" while its code was clean.
    # A checker that cannot run was reporting as if it had run and found
    # problems -- the failure mode this whole gate exists to remove.
    #
    # `src/**/__tests__/*` reaches the same files and is a legal include form.
    node -e "
      const cfg = JSON.parse(require('fs').readFileSync('tsconfig.json','utf8'));
      delete cfg.exclude;
      cfg.include = cfg.include || ['src/**/*'];
      cfg.include.push('src/**/__tests__/*','src/**/*.test.ts','src/**/*.spec.ts');
      require('fs').writeFileSync('$temp_tsconfig', JSON.stringify(cfg, null, 2));
    " 2>/dev/null
    local tsc_out tsc_exit
    tsc_out=$(_tsc_command --noEmit --project "$temp_tsconfig" --skipLibCheck 2>&1)
    tsc_exit=$?
    # The shared verdict below reads test_pass_exit; both tsc branches must feed
    # it or this one silently inherits whatever the previous branch left behind.
    test_pass_exit=$tsc_exit
    printf '%s\n' "$tsc_out" | head -30
    rm -f "$temp_tsconfig"
    # Distinguish "tsc evaluated the project and found type errors" from "tsc
    # rejected the config we generated and evaluated nothing". The verdict
    # contract requires those to be different states; conflating them spends the
    # user's time on our config and hides the real answer.
    #
    # Measured: with an INVALID config, tsc still checks every file it can see
    # and reports real errors ALONGSIDE the config complaint. So a TS5xxx line
    # alone does not mean "nothing was checked" -- it means nothing was checked
    # only when it is the ONLY thing reported. Which is why the test below is
    # "config error AND no type error", not "config error".
    if [ "$tsc_exit" -ne 0 ] && printf '%s\n' "$tsc_out" | grep -qE 'TS5[0-9][0-9][0-9]'; then
      # grep -E has no negative lookahead, so count instead of excluding:
      # every diagnostic is `error TS<digits>`, and a 5xxx code is a
      # configuration complaint rather than a type finding. If the totals match,
      # the only thing tsc said was "your config is bad".
      local all_err code_err
      all_err=$(printf '%s\n' "$tsc_out" | grep -cE 'error TS[0-9]+')
      code_err=$(printf '%s\n' "$tsc_out" | grep -cE 'error TS5[0-9][0-9][0-9]')
      if [ "$all_err" -gt 0 ] && [ "$all_err" -eq "$code_err" ]; then
        echo ""
        echo "⚠️  Gate 1: the generated test tsconfig was rejected by tsc — test files NOT checked."
        echo "   This is a defect in xp-gate's test-file pass, not in your code."
        return 2
      fi
    fi
  fi

  if [ "$test_pass_exit" -ne 0 ]; then
    echo ""
    echo "❌ BLOCKED - TYPE ERRORS in test files"
    echo "Your project's tsconfig.json excludes test files from type checking."
    echo "Add a tsconfig.tests.json to customise test file checking."
    return 1
  fi
  return 0
}

run_typescript_typecheck() {
  if ! command -v npx >/dev/null 2>&1; then
    echo "ℹ️  SKIP - npx not available (no TypeScript checker)"
    return 2
  fi

  local project_checker
  if project_checker=$(resolve_typecheck_command); then
    # Word-split deliberately on the command name only: `npm run <script>` from
    # package.json, or a user-set GATE_TS_TYPECHECK_CMD. Never a path list.
    local checker_argv=()
    read -r -a checker_argv <<< "$project_checker"
    echo "Running project typecheck (${project_checker})..."
    "${checker_argv[@]}" 2>&1 | head -30
    if [ "${PIPESTATUS[0]}" -ne 0 ]; then
      echo ""
      echo "❌ BLOCKED - TYPE ERRORS detected by the project's own typecheck script"
      echo "Fix the type errors above before committing."
      return 1
    fi
    echo "✅ PASSED - project typecheck."
    return 0
  fi

  # Verify tsc is the real compiler (npx may fetch the deprecated tsc@2.0.4 placeholder).
  local tsc_version
  tsc_version=$(_tsc_command --version 2>&1)
  if ! echo "$tsc_version" | grep -q "Version"; then
    echo "ℹ️  SKIP - tsc not properly installed ($tsc_version)"
    echo "Install typescript (npm install typescript --save-dev) for type checking."
    return 2
  fi

  if [ ! -f "tsconfig.json" ]; then
    echo "ℹ️  SKIP - tsconfig.json not found (no TypeScript project config)"
    return 2
  fi

  echo "Running TypeScript static analysis ($tsc_version)..."
  _tsc_command --noEmit --skipLibCheck 2>&1 | head -30
  if [ "${PIPESTATUS[0]}" -ne 0 ]; then
    echo ""
    echo "❌ BLOCKED - TYPE ERRORS detected"
    echo "Fix the type errors above before committing."
    return 1
  fi
  echo "✅ PASSED - TypeScript static analysis."

  if [ -d "src/__tests__" ] || [ -d "src/tests" ] || [ -d "tests" ] || [ -d "__tests__" ]; then
    run_test_file_pass || return 1
  fi
  return 0
}
