#!/usr/bin/env bash
# Deep Research - Environment setup (macOS + Debian/Ubuntu, using uv)
# Usage: bash scripts/setup.sh

set -euo pipefail

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

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

echo -e "${CYAN}============================================${RST}"
echo -e "${CYAN}  Deep Research - Setup (uv)${RST}"
echo -e "${CYAN}  Project root: ${PROJECT_ROOT}${RST}"
echo -e "${CYAN}============================================${RST}"

# -------- OS detection --------
OS="unknown"
case "$(uname -s)" in
    Darwin) OS="macos" ;;
    Linux)
        if [[ -f /etc/debian_version ]]; then
            OS="debian"
        elif [[ -f /etc/redhat-release ]]; then
            OS="rhel"
        else
            OS="linux"
        fi
        ;;
esac
echo -e "${YELLOW}Detected OS: ${OS}${RST}"

# -------- [1/4] uv check / install --------
echo ""
echo -e "${CYAN}[1/4] Checking uv...${RST}"

if ! command -v uv >/dev/null 2>&1; then
    echo -e "  ${YELLOW}uv not found. Installing...${RST}"
    echo -e "  ${YELLOW}(uv = fast Python package manager written in Rust, by Astral)${RST}"
    echo ""
    read -r -p "  Auto-install uv? [Y/n] " REPLY
    echo ""
    if [[ ! ${REPLY} =~ ^[Nn]$ ]]; then
        curl -LsSf https://astral.sh/uv/install.sh | sh
        # bring uv into current PATH
        [[ -f "${HOME}/.local/bin/uv" ]] && export PATH="${HOME}/.local/bin:${PATH}"
        if ! command -v uv >/dev/null 2>&1; then
            echo -e "  ${RED}ERROR: uv still not found after install.${RST}"
            echo "  Add ~/.local/bin to PATH, then re-run:"
            echo "    export PATH=\"\${HOME}/.local/bin:\${PATH}\""
            exit 1
        fi
    else
        echo -e "  ${RED}Manual install:${RST}"
        echo "    macOS:      brew install uv"
        echo "    all:        curl -LsSf https://astral.sh/uv/install.sh | sh"
        echo "    pip:        pip install --user uv"
        exit 1
    fi
fi

UV_VER="$(uv --version 2>&1 | head -1)"
echo -e "  ${GREEN}OK: ${UV_VER}${RST}"

# -------- [2/4] Python info --------
echo ""
echo -e "${CYAN}[2/4] Python check...${RST}"
if command -v python3 >/dev/null 2>&1; then
    SYS_PY="$(python3 --version 2>&1)"
    echo -e "  ${GREEN}System: ${SYS_PY} (uv manages its own Python 3.10+ automatically)${RST}"
else
    echo -e "  ${YELLOW}python3 not found in PATH (uv will download Python automatically)${RST}"
fi

# -------- [3/4] uv sync --------
echo ""
echo -e "${CYAN}[3/4] Syncing Python dependencies (uv sync)...${RST}"
echo -e "  ${YELLOW}First run may take a moment to download Python + packages.${RST}"
uv sync
echo -e "  ${GREEN}OK: .venv/ ready${RST}"

# -------- [4/4] System binaries --------
echo ""
echo -e "${CYAN}[4/4] Checking system binaries...${RST}"

check_bin() {
    local name="${1}"
    local install_macos="${2}"
    local install_debian="${3}"
    if command -v "${name}" >/dev/null 2>&1; then
        local ver
        ver="$("${name}" --version 2>&1 | head -1)"
        echo -e "  ${GREEN}OK: ${name} - ${ver}${RST}"
    else
        echo -e "  ${YELLOW}MISSING: ${name}${RST}"
        case "${OS}" in
            macos)  echo "    Install: ${install_macos}" ;;
            debian) echo "    Install: ${install_debian}" ;;
            *)      echo "    Install ${name} for your OS" ;;
        esac
    fi
}

check_bin "pandoc"   "brew install pandoc"                              "sudo apt install pandoc"
check_bin "opencode" "curl -fsSL https://opencode.ai/install | bash"   "curl -fsSL https://opencode.ai/install | bash"
check_bin "curl"     "pre-installed"                                    "sudo apt install curl"

# -------- Summary --------
echo ""
echo -e "${CYAN}============================================${RST}"
echo -e "${CYAN}  Setup complete${RST}"
echo -e "${CYAN}============================================${RST}"
echo ""

if [[ -f secrets.env ]]; then
    echo -e "${GREEN}OK: secrets.env found${RST}"
else
    echo -e "${YELLOW}TODO: create secrets.env${RST}"
    echo "  cp secrets.env.example secrets.env"
    echo "  # fill in ZENMUX_API_KEY etc."
fi

FONT_COUNT="$(find .opencode/templates/fonts -maxdepth 1 \( -name "*.otf" -o -name "*.ttf" \) 2>/dev/null | wc -l | tr -d ' ')"
if [[ "${FONT_COUNT}" -ge 7 ]]; then
    echo -e "${GREEN}OK: fonts ready (${FONT_COUNT} files)${RST}"
else
    echo -e "${YELLOW}TODO: download fonts (${FONT_COUNT}/7 present)${RST}"
    echo "  bash .opencode/templates/fonts/download-fonts.sh"
fi

echo ""
echo "Next steps:"
echo "  1. source scripts/activate.sh"
echo "  2. bash .opencode/templates/fonts/download-fonts.sh"
echo "  3. bash scripts/verify-zenmux.sh"
echo "  4. opencode"
echo ""
echo "Tips:"
echo "  Run a script directly:  uv run python .opencode/templates/report-template.py ..."
echo "  Add a package:          uv add <package>"
echo "  Upgrade all:            uv lock --upgrade && uv sync"
echo "  Full rebuild:           rm -rf .venv && bash scripts/setup.sh"
