#!/bin/sh
# ChatGPT subscription sign-in through Pi's OpenAI provider.
# The historical URL is retained for existing setup commands.
set -eu
BASE="${PI_SETUP_BASE:-https://onboarding.fornace.app}"
PROVIDER="openai"
MANUAL="/login $PROVIDER"
say() { printf '==> %s\n' "$*"; }
sub() { printf '    %s\n' "$*"; }
subscription_ready() {
  pi auth check --provider "$PROVIDER" --json |
    node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const a=JSON.parse(s);process.exit(a.status==="ready"&&a.authType==="oauth"?0:1)});'
}
if [ ! -t 0 ] || [ ! -t 1 ]; then
  say "ChatGPT sign-in requires your terminal and authorization."
  sub "In Pi, run: $MANUAL and choose Sign in with ChatGPT."
  exit 1
fi
if ! command -v pi >/dev/null 2>&1; then
  say "Install Pi first."
  sub "sh -c \"\$(curl -fsSL $BASE/bootstrap.sh)\""
  exit 1
fi
if subscription_ready; then
  say "ChatGPT subscription login is ready."
  exit 0
fi
AGENT_DIR="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
if [ -f "$AGENT_DIR/auth.json" ]; then
  BACKUP="$AGENT_DIR/backups/auth-before-chatgpt-$(date +%Y%m%dT%H%M%S)-$$.json"
  mkdir -p "$AGENT_DIR/backups"
  cp "$AGENT_DIR/auth.json" "$BACKUP"
  chmod 600 "$BACKUP"
fi
EXPECT_BIN=""
if command -v expect >/dev/null 2>&1; then EXPECT_BIN="$(command -v expect)"; fi
say "Sign in with your ChatGPT subscription."
sub "Choose Sign in with ChatGPT, authorize in your browser, then return to Pi."
sub "Existing Codex credentials are kept. OpenAI API-key credentials are backed up before sign-in."
sub "Quit Pi with /quit after authorization."
if [ -n "$EXPECT_BIN" ]; then
  "$EXPECT_BIN" -c '
    set timeout 60
    spawn pi
    expect {
      -re {[0-9]+\.[0-9]%/[0-9]+(\.[0-9]+)?[KM]} {}
      timeout { puts "Startup took longer than expected. In Pi run /login openai."; interact; exit }
      eof { exit 1 }
    }
    send -- "/login openai\r"
    expect {
      -ex {Select authentication method for OpenAI:} { sleep 1; send -- "\r" }
      timeout { puts "In Pi run /login openai and choose Sign in with ChatGPT." }
      eof { exit 1 }
    }
    interact
  '
else
  sub "In Pi, run $MANUAL and choose Sign in with ChatGPT."
  pi
fi
if subscription_ready; then
  say "ChatGPT subscription login is ready."
else
  say "ChatGPT authorization remains incomplete."
  sub "Run $MANUAL in Pi and choose Sign in with ChatGPT."
  exit 1
fi
