#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
LOCAL_ENV_FILE="${TDC114_SMOKE_ENV_FILE:-$ROOT_DIR/scripts/.env.android-device.local}"

if [ -f "$LOCAL_ENV_FILE" ]; then
  # shellcheck disable=SC1090
  source "$LOCAL_ENV_FILE"
fi

APP_API_BASE="${TDC114_API_BASE:-}"
if [ -z "$APP_API_BASE" ]; then
  echo "TDC114_API_BASE is required." >&2
  exit 64
fi

if [ -z "${TDC114_ADB_CONNECT_ADDRESS:-}" ] && [ -z "${ADB_SERVER_SOCKET:-}" ]; then
  echo "Either ADB_SERVER_SOCKET or TDC114_ADB_CONNECT_ADDRESS is required." >&2
  echo "Example: ADB_SERVER_SOCKET=tcp:172.21.128.1:5037 TDC114_FLUTTER_DEVICE_ID=ce091719b0a418620d7e $0" >&2
  exit 64
fi

if [ -n "${ADB_SERVER_SOCKET:-}" ] && [ -z "${TDC114_ADB_CONNECT_ADDRESS:-}" ] && [ -z "${TDC114_FLUTTER_DEVICE_ID:-}" ]; then
  echo "TDC114_FLUTTER_DEVICE_ID is required when using ADB_SERVER_SOCKET." >&2
  echo "Example: TDC114_FLUTTER_DEVICE_ID=ce091719b0a418620d7e" >&2
  exit 64
fi

SMOKE_PHONE="${TDC114_SMOKE_PHONE:-01091365338}"
BOOTSTRAP_API_BASE="${TDC114_SESSION_BOOTSTRAP_API_BASE:-$APP_API_BASE}"
BOOTSTRAP_API_BASE="${BOOTSTRAP_API_BASE//10.0.2.2/127.0.0.1}"
BOOTSTRAP_API_BASE="${BOOTSTRAP_API_BASE//localhost/127.0.0.1}"
DEVICE_ID="${TDC114_FLUTTER_DEVICE_ID:-$TDC114_ADB_CONNECT_ADDRESS}"
SKIP_SESSION_BOOTSTRAP="${TDC114_SKIP_SESSION_BOOTSTRAP:-false}"

tmp_body="$(mktemp)"
tmp_err="$(mktemp)"
trap 'rm -f "$tmp_body" "$tmp_err"' EXIT

DEFINE_ARGS=(
  "--dart-define=TDC114_API_BASE=${APP_API_BASE}"
)

append_optional_define() {
  local key="$1"
  local value="${!key:-}"
  if [ -n "$value" ]; then
    DEFINE_ARGS+=("--dart-define=${key}=${value}")
  fi
}

append_optional_define "SSO_BASE_URL"
append_optional_define "TDC114_AUTH_API_BASE"
append_optional_define "TDC114_DIRECTORY_API_BASE"
append_optional_define "TDC114_ORGANIZATION_API_BASE"
append_optional_define "TDC114_ORG_CONTEXT_API_BASE"
append_optional_define "TDC114_ORG_CONTEXT_TENANT_SLUG"

if [ "$SKIP_SESSION_BOOTSTRAP" = "1" ] || [ "$SKIP_SESSION_BOOTSTRAP" = "true" ]; then
  echo "Skipping session bootstrap; app will open its normal login flow." >&2
else
  login_payload="$(printf '{"phoneNumber":"%s","device":{"platform":"android","appVersion":"manual-smoke","deviceName":"android-manual"}}' "$SMOKE_PHONE")"

  set +e
  http_code="$(
    curl -sS \
      -o "$tmp_body" \
      -w '%{http_code}' \
      -H 'content-type: application/json' \
      -d "$login_payload" \
      "${BOOTSTRAP_API_BASE%/}/api/v1/tdc114plus/auth/phone-login" 2>"$tmp_err"
  )"
  curl_status=$?
  set -e

  if [ "$curl_status" -eq 0 ] && [ "$http_code" = "200" ]; then
    mapfile -t exported < <(
      python3 - "$tmp_body" <<'PY'
import json
import sys

with open(sys.argv[1], 'r', encoding='utf-8') as fh:
    data = json.load(fh)

user = data.get("user") or {}
fields = {
    "TDC114_PREAUTH_TOKEN": data.get("token", ""),
    "TDC114_PREAUTH_EXPIRES_AT": data.get("expiresAt", ""),
    "TDC114_PREAUTH_USER_ID": user.get("id", ""),
    "TDC114_PREAUTH_USER_NAME": user.get("name", ""),
    "TDC114_PREAUTH_USER_PHONE": user.get("phoneNumber", ""),
    "TDC114_PREAUTH_TENANT_ID": user.get("tenantId", ""),
    "TDC114_PREAUTH_TENANT_NAME": user.get("tenantName", ""),
    "TDC114_PREAUTH_TENANT_SLUG": user.get("tenantSlug", ""),
    "TDC114_PREAUTH_DEPARTMENT": user.get("department", "") or "",
    "TDC114_PREAUTH_GRADE": user.get("grade", "") or "",
    "TDC114_PREAUTH_POSITION": user.get("position", "") or "",
    "TDC114_PREAUTH_JOB_TITLE": user.get("jobTitle", "") or "",
}

for key, value in fields.items():
    print(f"{key}={value}")
PY
    )
    for entry in "${exported[@]}"; do
      DEFINE_ARGS+=("--dart-define=${entry}")
    done
    echo "Using real local phone-login bootstrap for manual post-login run." >&2
  else
    echo "WARN local phone-login bootstrap failed; using mock directory fallback." >&2
    if [ -s "$tmp_err" ]; then
      cat "$tmp_err" >&2
    fi
    if [ -s "$tmp_body" ]; then
      cat "$tmp_body" >&2
    fi
    DEFINE_ARGS+=(
      "--dart-define=TDC114_SMOKE_USE_MOCK_DIRECTORY=true"
      "--dart-define=TDC114_PREAUTH_TOKEN=mock-session-token"
      "--dart-define=TDC114_PREAUTH_EXPIRES_AT=2099-12-31T23:59:59Z"
      "--dart-define=TDC114_PREAUTH_USER_ID=user-001"
      "--dart-define=TDC114_PREAUTH_USER_NAME=김하늘"
      "--dart-define=TDC114_PREAUTH_USER_PHONE=+821012345678"
      "--dart-define=TDC114_PREAUTH_TENANT_ID=tenant-hanmac"
      "--dart-define=TDC114_PREAUTH_TENANT_NAME=한맥"
      "--dart-define=TDC114_PREAUTH_TENANT_SLUG=hanmac"
      "--dart-define=TDC114_PREAUTH_DEPARTMENT=기술연구소"
      "--dart-define=TDC114_PREAUTH_GRADE=책임"
      "--dart-define=TDC114_PREAUTH_POSITION=팀장"
      "--dart-define=TDC114_PREAUTH_JOB_TITLE=Flutter 개발"
    )
  fi
fi

echo "Launching app on device ${DEVICE_ID} with post-login seed..." >&2
exec "$ROOT_DIR/scripts/flutter-docker.sh" \
  run \
  -d "$DEVICE_ID" \
  "${DEFINE_ARGS[@]}"
