#!/bin/bash

# shellcheck shell=bash

ai_choose_provider() {
  local primary="${AI_PRIMARY_PROVIDER:-anthropic}"
  primary="$(printf '%s' "$primary" | tr '[:upper:]' '[:lower:]')"
  if [[ "$primary" == "openai" ]]; then
    if [[ -n "${OPENAI_API_KEY-}" ]]; then
      echo "openai"
      return 0
    fi
    if [[ -n "${ANTHROPIC_API_KEY-}" ]]; then
      echo "anthropic"
      return 0
    fi
  else
    if [[ -n "${ANTHROPIC_API_KEY-}" ]]; then
      echo "anthropic"
      return 0
    fi
    if [[ -n "${OPENAI_API_KEY-}" ]]; then
      echo "openai"
      return 0
    fi
  fi
  return 1
}

# AI generate name from base64 content
bridge_ai_generate_name_from_base64() {
  if [[ -z "${1:-}" ]]; then
    json_error "Base64 content required"
    return 1
  fi
  content_b64="$1"
  load_ai_primary_provider
  load_openai_model
  load_openai_api_key
  load_anthropic_api_key
  local provider
  if ! provider="$(ai_choose_provider)"; then
    echo "\"missing_api_key\""
    return 0
  fi
  # Build request via Python to ensure proper JSON encoding
  request_payload=$(python3 - "$content_b64" "$provider" "${OPENAI_MODEL:-gpt-4o-mini}" <<'PY'
import sys, json, base64, re

b64 = sys.argv[1]
provider = sys.argv[2] if len(sys.argv) > 2 else "anthropic"
openai_model = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "gpt-4o-mini"
try:
    content = base64.b64decode(b64.encode('utf-8')).decode('utf-8', 'ignore')
except Exception:
    content = ''

def extract_command(line: str) -> str:
    stripped = line.strip()
    for lead in ("$ ", "> "):
        if stripped.startswith(lead):
            return stripped[len(lead):].strip()
    for marker in ("$ ", "# "):
        if marker in line:
            return line.split(marker)[-1].strip()
    return ""

lines = content.splitlines()
last_cmd = ""
for line in reversed(lines):
    candidate = extract_command(line)
    if candidate:
        last_cmd = candidate
        break

prompt = f"""Analyze this terminal session and create a descriptive name based ONLY on the console output and commands executed.

Terminal output:
{content}

IMPORTANT: Look carefully at the terminal output for:
1. Commands that were executed (lines starting with $ or > or commands after prompts)
2. Application output patterns (errors, build messages, server logs)
3. Tool-specific output (git commands, npm/yarn, docker, ssh, etc.)
4. AI coding assistant interactions (Claude Code, OpenCode, Cursor, etc.)
5. Git-specific patterns and outputs

CRITICAL GIT DETECTION: Check for ANY of these Git indicators in the last outputs:
- Git commands: git status, git diff, git add, git commit, git push, git pull, git checkout, git branch, git merge, git rebase, git log, git stash, etc.
- Git output patterns: "On branch", "Your branch is", "Changes not staged", "Changes to be committed", "Untracked files", "modified:", "deleted:", "new file:", "renamed:"
- Git diff output: Lines starting with +, -, @@, diff --git
- Git merge/rebase messages: "CONFLICT", "Merge branch", "Rebase", "Cherry-pick"
- Git status indicators: "nothing to commit", "working tree clean", "ahead of", "behind"
- Git error messages: "fatal:", "error:", "warning:" (when preceded by git commands)

DESCRIPTION ONLY: Return a short description of the activity.
- Do NOT include the app/tool name or any prefix in the output.
- If Git patterns are detected, the description should still reflect the git activity, but do not add "git_".

Describe what the user was actually doing based on the console output, not just the current state.

The name should be max 100 chars total, use underscores only (no colons or special chars).

Respond with ONLY the session name, nothing else."""

if provider == "openai":
    req = {
        "model": openai_model,
        "max_tokens": 100,
        "temperature": 0.2,
        "messages": [{"role": "user", "content": prompt}],
    }
else:
    req = {
        "model": "claude-3-5-haiku-latest",
        "max_tokens": 100,
        "messages": [{"role": "user", "content": prompt}],
    }
print(json.dumps(req))
PY
  )
  request_body="$request_payload"
  if [[ "$provider" == "openai" ]]; then
    response=$(curl -s -X POST https://api.openai.com/v1/chat/completions \
      --max-time 20 \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $OPENAI_API_KEY" \
      -d "$request_body" 2>/dev/null)
    new_name=$(echo "$response" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('choices',[{}])[0].get('message',{}).get('content',''))" 2>/dev/null)
  else
    response=$(curl -s -X POST https://api.anthropic.com/v1/messages \
      --max-time 20 \
      -H "Content-Type: application/json" \
      -H "x-api-key: $ANTHROPIC_API_KEY" \
      -H "anthropic-version: 2023-06-01" \
      -d "$request_body" 2>/dev/null)
    new_name=$(echo "$response" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('content',[{}])[0].get('text',''))" 2>/dev/null)
  fi
  # Clean and truncate
  new_name=$(echo "$new_name" | tr ' ' '_' | sed 's/[^a-zA-Z0-9_-]//g' | cut -c1-100)
  if [[ -z "$new_name" ]]; then
    echo "\"ai_generation_failed\""
  else
    new_name="${new_name:0:100}"
    printf '"%s"\n' "$new_name"
  fi
}

# Rename session with AI
bridge_rename_session() {
  if [[ -z "${1:-}" ]]; then
    json_error "Session name required"
    return 1
  fi
  original_session_name="$1"

  clear_auto_rename_requested() {
    if tmux_available && tmux_session_exists "$original_session_name"; then
      tmux set-option -qu -t "$original_session_name" @orchestra_auto_rename_requested >/dev/null 2>&1 || true
    fi
  }

  # Load API key from config file or fallback to .env
  load_openai_api_key
  load_anthropic_api_key

  if [[ -z "${OPENAI_API_KEY-}" && -z "${ANTHROPIC_API_KEY-}" ]]; then
    clear_auto_rename_requested
    echo "\"missing_api_key\""
    return 0
  fi

  # Check if tmux is available and session exists
  if ! tmux_available; then
    echo "\"tmux_not_available\""
    return 0
  fi

  if ! tmux_session_exists "$original_session_name"; then
    echo "\"session_not_found\""
    return 0
  fi

  # Generate AI description using the CURRENT session (no renaming to temp name)
  local err_file
  if [[ "$OSTYPE" == "darwin"* ]]; then
    err_file=$(mktemp -t gw_ai_err)
  else
    err_file=$(mktemp)
  fi
  local ai_status=0
  if ! ai_name="$(tmux_generate_ai_session_name "$original_session_name" 2>"$err_file")"; then
    ai_status=$?
  fi
  local ai_err=""
  if [[ -s "$err_file" ]]; then
    ai_err=$(tail -n 1 "$err_file")
  fi
  rm -f "$err_file"

  if [[ -n "$ai_name" ]]; then
    # Clean the AI description for session naming
    ai_name="$(echo "$ai_name" | tr ' ' '_' | sed 's/[^a-zA-Z0-9_-]//g' | cut -c1-100)"
    ai_name="$(echo "$ai_name" | sed 's/^_*//')"
    if [[ -z "$ai_name" ]]; then
      clear_auto_rename_requested
      echo "\"ai_generation_failed\""
      return 0
    fi

    # Perform the rename preserving canonical prefix and delimiter
    if tmux_rename_session "$original_session_name" "$ai_name" >/dev/null; then
      echo "\"success\""
    else
      clear_auto_rename_requested
      echo "\"rename_failed\""
    fi
  else
    # AI generation failed, keep original name
    clear_auto_rename_requested
    if [[ -n "$ai_err" ]]; then
      echo "\"ai_generation_failed: ${ai_err}\""
    elif [[ $ai_status -ne 0 ]]; then
      echo "\"ai_generation_failed: ai helper exited ${ai_status}\""
    else
      echo "\"ai_generation_failed\""
    fi
  fi
}

# Manual rename session
bridge_manual_rename_session() {
  if [[ -z "${1:-}" ]] || [[ $# -lt 2 ]]; then
    json_error "Old and new session names required"
    return 1
  fi
  old_name="$1"
  shift
  new_display_name="$*"

  if ! tmux_available; then
    echo "\"tmux_not_available\""
    return 0
  fi

  # Check if session exists
  if ! tmux has-session -t "$old_name" 2>/dev/null; then
    echo "\"session_not_found\""
    return 0
  fi
  new_display_name="$(printf '%s' "$new_display_name" | tr ' ' '_' | sed 's/[^a-zA-Z0-9_]/_/g' | cut -c1-100)"

  # Validate new display name after matching the TUI's sanitization rules.
  if [[ -z "$new_display_name" || ! "$new_display_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
    echo "\"invalid_name\""
    return 0
  fi

  # Perform rename via tmux API to preserve delimiter and canonical prefix
  if tmux_rename_session "$old_name" "$new_display_name" >/dev/null; then
    echo "\"success\""
  else
    echo "\"rename_failed\""
  fi
}
