#!/bin/bash
# pi-skill - Integrated backup for pi agent
# Combines: Agent-Pi + Plannotator + Open Design + RTK

set -e

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

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

PI_DIR="${PI_DIR:-$HOME/.pi/agent}"
SKILLS_DIR="$SOURCE_DIR/skills"
EXT_DIR="$PI_DIR/extensions"
SETTINGS_FILE="$PI_DIR/settings.json"

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║       pi-skill Installation                                 ║${NC}"
echo -e "${BLUE}║       Agent-Pi + Plannotator + Open Design + RTK             ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Repos
AGENT_PI_REPO="https://github.com/ruizrica/agent-pi.git"
PLANNOTATOR_REPO="https://github.com/backnotprop/plannotator.git"
OPEN_DESIGN_REPO="https://github.com/nexu-io/open-design.git"
RTK_REPO="https://github.com/mcowger/pi-rtk.git"

# Dirs
AGENT_PI_DIR="$SOURCE_DIR/.repos/agent-pi"
PLANNOTATOR_DIR="$SOURCE_DIR/.repos/plannotator"
OPEN_DESIGN_DIR="$SOURCE_DIR/.repos/open-design"
RTK_DIR="$EXT_DIR/pi-rtk"

#######################################
# Clone/Update repos
#######################################
echo -e "${CYAN}[1/7] Cloning repositories...${NC}"

clone_or_update() {
    local repo=$1
    local dir=$2
    local name=$(basename $dir)
    
    if [ -d "$dir/.git" ]; then
        echo -e "  ${YELLOW}Updating${NC} $name..."
        git -C "$dir" pull --ff origin main 2>/dev/null || git -C "$dir" pull --ff origin master 2>/dev/null
    else
        echo -e "  ${GREEN}Cloning${NC} $name..."
        rm -rf "$dir"
        git clone --depth 1 "$repo" "$dir"
    fi
}

mkdir -p "$SOURCE_DIR/.repos"
clone_or_update "$AGENT_PI_REPO" "$AGENT_PI_DIR"
clone_or_update "$PLANNOTATOR_REPO" "$PLANNOTATOR_DIR"
clone_or_update "$OPEN_DESIGN_REPO" "$OPEN_DESIGN_DIR"

# RTK goes to extensions
mkdir -p "$EXT_DIR"
clone_or_update "$RTK_REPO" "$RTK_DIR"

echo ""

#######################################
# Install Agent-Pi (using its installer)
#######################################
echo -e "${CYAN}[2/7] Installing Agent-Pi...${NC}"
cd "$AGENT_PI_DIR" && ./install.sh 2>&1 | tail -15
cd "$SOURCE_DIR"

echo ""

#######################################
# Install Plannotator (via npm)
#######################################
echo -e "${CYAN}[3/7] Installing Plannotator...${NC}"
pi install npm:@plannotator/pi-extension 2>&1 | tail -5
cd "$SOURCE_DIR"

echo ""

#######################################
# Install Skills
# pi-skill is a Pi package (package.json declares "pi": { "skills": ["./skills"] }).
# Pi auto-discovers skills from installed packages — no manual copying needed.
# We just need to populate pi-skill/skills/ with external skills.
#######################################
echo -e "${CYAN}[4/7] Installing skills...${NC}"

mkdir -p "$SOURCE_DIR/skills"

# Open Design skills → pi-skill/skills/ (Pi discovers them from the pi-skill package)
echo -e "  ${YELLOW}Installing${NC} Open Design skills..."
if [ -d "$OPEN_DESIGN_DIR/skills" ]; then
    for skill_dir in "$OPEN_DESIGN_DIR/skills"/*/; do
        if [ -d "$skill_dir" ] && [ -f "${skill_dir}SKILL.md" ]; then
            skill_name=$(basename "$skill_dir")
            if [ ! -d "$SOURCE_DIR/skills/$skill_name" ]; then
                echo -e "    ${GREEN}✓${NC} $skill_name"
                cp -r "$skill_dir" "$SOURCE_DIR/skills/" 2>/dev/null || true
            fi
        fi
    done
fi

# Create design workflow skill
mkdir -p "$SOURCE_DIR/skills/design-workflow"
cat > "$SOURCE_DIR/skills/design-workflow/SKILL.md" << 'SKILL_EOF'
# Design Workflow Skill

Design-first workflow using Open Design patterns.

## Usage

```
/design <brief>     - Start design workflow
/design-brief       - Show brief form questions
/design-directions  - Show visual direction options
/open-design        - Open Open Design UI
```

## Workflow

1. **Brief** - Define surface, audience, tone, brand context
2. **Directions** - Pick from 5 visual schools
3. **Build** - Generate artifacts using selected design system
4. **Critique** - 5-dimension self-check
5. **Export** - HTML, PDF, PPT, MP4

## Auto-Detection

Design intent auto-triggers DESIGN mode.

## Visual Directions

| School | Description |
|--------|-------------|
| Editorial Monocle | High-contrast serif, magazine layouts |
| Modern Minimal | Clean lines, ample whitespace |
| Warm Soft | Rounded corners, soft gradients |
| Tech Utility | Mono fonts, dense information |
| Brutalist Experimental | Raw, bold, unconventional |
SKILL_EOF

echo ""

#######################################
# Install Agents
#######################################
echo -e "${CYAN}[5/7] Installing agents...${NC}"

mkdir -p "$PI_DIR/agents"

# Copy builder agents from Agent-Pi
if [ -d "$AGENT_PI_DIR/agents" ]; then
    for agent_file in "$AGENT_PI_DIR/agents"/*.md; do
        if [ -f "$agent_file" ]; then
            agent_name=$(basename "$agent_file")
            echo -e "  ${GREEN}✓${NC} $agent_name"
            cp "$agent_file" "$PI_DIR/agents/" 2>/dev/null || true
        fi
    done
fi

echo ""

#######################################
# Update Settings
# Register pi-skill as a Pi package so its skills are auto-discovered.
#######################################
echo -e "${CYAN}[6/7] Updating settings...${NC}"

cat > "$SETTINGS_FILE" << 'SETTINGS_EOF'
{
  "lastChangelogVersion": "0.75.5",
  "defaultProvider": "deepseek",
  "defaultModel": "deepseek-v4-flash",
  "defaultThinkingLevel": "high",
  "terminal": {
    "showTerminalProgress": true
  },
  "packages": [
    "git:github.com/ruizrica/agent-pi",
    "npm:@plannotator/pi-extension"
  ],
  "quietStartup": true,
  "theme": "midnight-ocean"
}
SETTINGS_EOF

# Register pi-skill itself as a Pi package so Pi discovers skills/skills/ automatically
echo -e "  ${YELLOW}Registering${NC} pi-skill as Pi package..."
pi install "$SOURCE_DIR" 2>&1 | tail -3

echo ""

#######################################
# Final Setup
#######################################
echo -e "${CYAN}[7/7] Final setup...${NC}"

mkdir -p "$SOURCE_DIR/backups"

echo ""

#######################################
# Summary
#######################################
echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║       Installation Complete!                                  ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "Extensions: ${BLUE}43+${NC} (Agent-Pi)"
echo -e "Skills: ${BLUE}100+${NC} (Open Design + pi-skill)"
echo -e "Agents: ${BLUE}24+${NC} (Agent-Pi)"
echo -e "RTK: ${BLUE}✓${NC}"
echo ""
echo -e "${CYAN}Commands:${NC}"
echo -e "  ${BLUE}/mode${NC}                  - Show current mode"
echo -e "  ${BLUE}Shift+Tab${NC}              - Cycle modes"
echo -e "  ${BLUE}Ctrl+X${NC}                - Cycle themes"
echo -e "  ${BLUE}/agents-team${NC}          - Switch teams"
echo -e "  ${BLUE}/chain${NC}                - Switch chains"
echo ""
echo -e "${CYAN}Modes:${NC}"
echo -e "  ${BLUE}NORMAL → PLAN → SPEC → PIPELINE → TEAM → CHAIN${NC}"
echo ""
echo -e "${YELLOW}Restart pi agent to load all extensions${NC}"
echo ""
#######################################
# Patch plan-viewer for comment support
#######################################
patch_plan_viewer() {
    local PLAN_VIEWER_HTML="$AGENT_PI_DIR/extensions/lib/plan-viewer-html.ts"
    local PLAN_VIEWER_TS="$AGENT_PI_DIR/extensions/plan-viewer.ts"
    
    echo -e "${CYAN}[*] Patching plan-viewer for comment support...${NC}"
    
    # Check if already patched
    if grep -q "comment-section" "$PLAN_VIEWER_HTML" 2>/dev/null; then
        echo -e "${YELLOW}  Already patched, skipping${NC}"
        return
    fi
    
    # Patch plan-viewer-html.ts
    # Add CSS for comment section
    sed -i '' 's/body.approved-state \.footer-wrapper { display: none; }/body.approved-state .footer-wrapper { display: none; }\n\n  \/* ── Comment Section ────────────────────────── *\/\n  .comment-section {\n    display: none;\n    padding: 12px 16px;\n    border-top: 1px solid var(--border);\n    background: var(--surface);\n  }\n  .comment-section.visible { display: block; }\n  .comment-section label {\n    display: block;\n    font-size: 12px;\n    font-weight: 500;\n    color: var(--text-muted);\n    margin-bottom: 6px;\n  }\n  .comment-section textarea {\n    width: 100%;\n    min-height: 80px;\n    padding: 10px 12px;\n    background: var(--bg);\n    border: 1px solid var(--border);\n    border-radius: 6px;\n    color: var(--text);\n    font-family: var(--font);\n    font-size: 14px;\n    line-height: 1.5;\n    resize: vertical;\n  }\n  .comment-section textarea:focus {\n    outline: none;\n    border-color: var(--accent);\n  }\n  .comment-section textarea::placeholder {\n    color: var(--text-dim);\n  }\n  .comment-section .comment-hint {\n    font-size: 11px;\n    color: var(--text-dim);\n    margin-top: 4px;\n  }/' "$PLAN_VIEWER_HTML"
    
    # Add comment section HTML
    sed -i '' 's/<div class="footer-wrapper">/<div class="footer-wrapper" id="footerWrapper">\n  <div class="comment-section" id="commentSection">\n    <label for="commentInput">Add feedback or comments (optional)<\/label>\n    <textarea id="commentInput" placeholder="Enter your feedback, questions, or suggested changes..."><\/textarea>\n    <div class="comment-hint">Your comments will be attached when declining the plan.<\/div>\n  <\/div>\n  <div class="footer">/' "$PLAN_VIEWER_HTML"
    
    # Add comment toggle button
    sed -i '' 's/<button class="btn" onclick="decline()" id="btnDecline">Close<\/button>/<button class="btn btn-ghost" onclick="toggleCommentSection()" id="btnComment" title="Add comment">💬 Comment<\/button>\n    <button class="btn" onclick="decline()" id="btnDecline">Close<\/button>/' "$PLAN_VIEWER_HTML"
    
    echo -e "${GREEN}  ✓ Plan viewer HTML patched${NC}"
}
