#!/bin/bash
# UnlimitedCoding — Codex CLI Installer
# Downloads Codex binary from GitHub + applies config patches
#
# Usage:
#   curl -fsSL https://git.sensey24.ru/.../ucodex_install.sh | sudo bash

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

echo -e "${BOLD}=== UnlimitedCoding — Codex CLI Installer ===${NC}"

# Check prerequisites
for cmd in python3 curl; do
    if ! command -v "$cmd" &>/dev/null; then
        echo -e "${RED}Error: $cmd is required but not found${NC}"
        exit 1
    fi
done

# Check Python version (need 3.11+ for tomllib)
PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
PY_MAJOR=$(echo "$PY_VER" | cut -d. -f1)
PY_MINOR=$(echo "$PY_VER" | cut -d. -f2)
if [ "$PY_MAJOR" -lt 3 ] || ([ "$PY_MAJOR" -eq 3 ] && [ "$PY_MINOR" -lt 11 ]); then
    echo -e "${RED}Error: Python 3.11+ required (found $PY_VER)${NC}"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Step 1: Install/update Codex binary
echo -e "\n${BOLD}Step 1: Installing Codex CLI binary...${NC}"
if [ -f "$SCRIPT_DIR/update-codex.sh" ]; then
    bash "$SCRIPT_DIR/update-codex.sh"
else
    echo -e "${RED}update-codex.sh not found${NC}"
    exit 1
fi

# Step 2: Apply config patches
echo -e "\n${BOLD}Step 2: Applying config patches...${NC}"
if [ ! -f "$SCRIPT_DIR/codex_config.json" ]; then
    echo -e "${YELLOW}codex_config.json not found, copying example...${NC}"
    cp "$SCRIPT_DIR/codex_config.example.json" "$SCRIPT_DIR/codex_config.json"
    echo -e "${YELLOW}Edit codex_config.json with your API endpoint and key, then re-run.${NC}"
    exit 1
fi

python3 "$SCRIPT_DIR/codex_patcher.py" --apply --config "$SCRIPT_DIR/codex_config.json"

# Step 3: Validate
echo -e "\n${BOLD}Step 3: Validating...${NC}"
python3 "$SCRIPT_DIR/update_codex_patcher.py" --validate

echo -e "\n${GREEN}=== Installation complete! ===${NC}"
echo -e "Run: ${CYAN}codex${NC} to start"
