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

# CertiSigma Census — Build, Test & Publish Automation
# Usage:
#   ./deploy.sh          Run tests and build package
#   ./deploy.sh publish   Build + publish to PyPI (requires confirmation)

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
MIN_PYTHON="3.10"

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

step()  { echo -e "\n${CYAN}▸ $1${NC}"; }
ok()    { echo -e "${GREEN}  ✓ $1${NC}"; }
warn()  { echo -e "${YELLOW}  ⚠ $1${NC}"; }
fail()  { echo -e "${RED}  ✗ $1${NC}"; exit 1; }

# ── 1. Pre-flight checks ────────────────────────────────────────────
step "Pre-flight checks"

cd "$PROJECT_DIR"

python_version=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
if python3 -c "
import sys
min_parts = [int(x) for x in '$MIN_PYTHON'.split('.')]
if sys.version_info[:2] < tuple(min_parts):
    sys.exit(1)
"; then
    ok "Python $python_version (>= $MIN_PYTHON)"
else
    fail "Python $python_version is below minimum $MIN_PYTHON"
fi

if command -v git &>/dev/null && git rev-parse --is-inside-work-tree &>/dev/null; then
    ok "Git repository detected"
else
    fail "Not a git repository"
fi

if [ -f pyproject.toml ]; then
    ok "pyproject.toml found"
else
    fail "pyproject.toml not found — wrong directory?"
fi

# ── 2. Install dependencies ─────────────────────────────────────────
step "Installing dependencies (editable + dev)"

pip install -e ".[dev]" --quiet 2>&1 | tail -1 || true
ok "Dependencies installed"

# ── 3. Run test suite ────────────────────────────────────────────────
step "Running test suite"

if pytest --tb=short -q; then
    ok "All tests passed"
else
    fail "Tests failed — fix before deploying"
fi

# ── 4. Build package ────────────────────────────────────────────────
step "Building package"

pip install build --quiet 2>&1 | tail -1 || true
rm -rf dist/
python3 -m build --quiet 2>&1
built_files=$(ls dist/ 2>/dev/null | wc -l)
if [ "$built_files" -ge 2 ]; then
    ok "Built $(ls dist/)"
else
    fail "Build produced unexpected output"
fi

# ── 5. Publish (optional) ───────────────────────────────────────────
if [ "${1:-}" = "publish" ]; then
    step "Publishing to PyPI"

    if ! command -v twine &>/dev/null; then
        pip install twine --quiet
    fi

    version=$(python3 -c "from certisigma_census import __version__; print(__version__)")
    echo -e "  Package version: ${YELLOW}$version${NC}"

    if git diff --quiet && git diff --cached --quiet; then
        ok "Working tree clean"
    else
        fail "Uncommitted changes — commit before publishing"
    fi

    echo ""
    read -rp "  Publish certisigma-census $version to PyPI? [y/N] " confirm
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
        git tag -a "v$version" -m "Release $version" 2>/dev/null || warn "Tag v$version already exists"
        git push origin main --tags
        twine upload dist/*
        ok "Published v$version to PyPI"
    else
        warn "Publish cancelled"
    fi
fi

# ── Summary ──────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}  Census build complete${NC}"
echo -e "  Artifacts: ${CYAN}dist/${NC}"
echo -e "  To publish: ${CYAN}./deploy.sh publish${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
