#!/bin/bash
set -euo pipefail

# ============================================================================
# Setup - Linear Insights Configuration Management
# ============================================================================
# Initialize, refresh, and manage Linear Insights configuration.
# Queries Linear MCP for teams, projects, and users to populate config.yaml.
#
# Operations:
#   --init        Initialize config.yaml from Linear API
#   --refresh     Update project/team IDs from Linear (preserves custom settings)
#   --validate    Validate existing config against Linear
#   --show        Display current configuration
#   --clear-cache Clear all cached data
#
# Data Sources:
#   - Linear MCP: mcp__linear-server__list_teams
#   - Linear MCP: mcp__linear-server__list_projects
#   - Linear MCP: mcp__linear-server__list_users
# ============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/config.yaml"
CONFIG_BACKUP="$SCRIPT_DIR/config.yaml.backup"
CACHE_DIR="$SCRIPT_DIR/.cache"

# ============================================================================
# Usage
# ============================================================================

usage() {
    cat << EOF
Usage: $(basename "$0") [OPERATION] [OPTIONS]

Initialize, refresh, and manage Linear Insights configuration.

Operations:
  --init           Create new config.yaml from Linear API data
  --refresh        Update project/team IDs from Linear (preserves custom settings)
  --validate       Validate config.yaml against Linear API
  --show           Display current configuration
  --clear-cache    Clear all cached data (.cache directory)

Options:
  --backup         Create backup before modifying config (used with --init, --refresh)
  --json           Output as JSON instead of markdown
  -h, --help       Show this help

Examples:
  # Initialize configuration from Linear
  $(basename "$0") --init

  # Show current configuration
  $(basename "$0") --show

  # Validate configuration against Linear
  $(basename "$0") --validate

  # Refresh project IDs (preserves shortcuts, weights)
  $(basename "$0") --refresh

  # Clear cache
  $(basename "$0") --clear-cache

  # Initialize with backup
  $(basename "$0") --init --backup

  # JSON output for programmatic use
  $(basename "$0") --show --json

MCP Queries (--init mode):
  The --init operation will instruct you to run these Linear MCP queries:
    1. mcp__linear-server__list_teams()
    2. mcp__linear-server__list_projects()
    3. mcp__linear-server__list_users()

  Results are used to generate config.yaml with:
    - Team IDs and keys
    - Project IDs and names
    - User IDs and emails

Configuration Location:
  $CONFIG_FILE

Cache Location:
  $CACHE_DIR/
    linear_cache.json    - TTL-based Linear data cache
    snapshots/           - Daily project snapshots

EOF
    exit 0
}

# ============================================================================
# Argument Parsing
# ============================================================================

OPERATION=""
BACKUP=false
JSON_OUTPUT=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --init)
            OPERATION="init"
            shift
            ;;
        --refresh)
            OPERATION="refresh"
            shift
            ;;
        --validate)
            OPERATION="validate"
            shift
            ;;
        --show)
            OPERATION="show"
            shift
            ;;
        --clear-cache)
            OPERATION="clear-cache"
            shift
            ;;
        --backup)
            BACKUP=true
            shift
            ;;
        --json)
            JSON_OUTPUT=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Error: Unknown argument: $1"
            echo ""
            usage
            ;;
    esac
done

# Require an operation
if [[ -z "$OPERATION" ]]; then
    echo "Error: No operation specified."
    echo ""
    usage
fi

# ============================================================================
# Helper Functions
# ============================================================================

# Output markdown only when not in JSON mode
md_echo() {
    if [[ "$JSON_OUTPUT" != "true" ]]; then
        echo "$@"
    fi
}

# Check if config file exists
config_exists() {
    [[ -f "$CONFIG_FILE" ]]
}

# Create backup of existing config
backup_config() {
    if config_exists; then
        cp "$CONFIG_FILE" "$CONFIG_BACKUP"
        md_echo "Backup created: $CONFIG_BACKUP"
    fi
}

# Parse YAML value (simple single-line values only)
parse_yaml_value() {
    local key="$1"
    grep -E "^[[:space:]]*$key:" "$CONFIG_FILE" 2>/dev/null | head -1 | \
        sed 's/.*:[[:space:]]*//' | \
        sed 's/^"//' | sed 's/"$//' | \
        sed "s/^'//" | sed "s/'$//"
}

# Get all project shortcuts from config
get_project_shortcuts() {
    awk '
        /^projects:/ { in_projects=1; next }
        in_projects && /^[[:space:]][[:space:]][A-Z][a-zA-Z]+:/ {
            gsub(/^[[:space:]]+/, "")
            gsub(/:.*/, "")
            print
        }
        in_projects && /^[a-z]+:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get project ID for a given shortcut
get_project_id() {
    local project="$1"
    awk -v proj="$project" '
        /^[[:space:]]+'"$project"':/ { in_project=1; next }
        in_project && /^[[:space:]]+id:/ {
            gsub(/.*id:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_project && /^[[:space:]][[:space:]][A-Za-z]+:/ && !/^[[:space:]]+id:/ && !/^[[:space:]]+name:/ && !/^[[:space:]]+shortcuts:/ && !/^[[:space:]]+status:/ && !/^[[:space:]]+lead:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get project name for a given shortcut
get_project_name() {
    local project="$1"
    awk -v proj="$project" '
        /^[[:space:]]+'"$project"':/ { in_project=1; next }
        in_project && /^[[:space:]]+name:/ {
            gsub(/.*name:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_project && /^[[:space:]][[:space:]][A-Za-z]+:/ && !/^[[:space:]]+id:/ && !/^[[:space:]]+name:/ && !/^[[:space:]]+shortcuts:/ && !/^[[:space:]]+status:/ && !/^[[:space:]]+lead:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get team ID
get_team_id() {
    local team="$1"
    awk -v team="$team" '
        /^[[:space:]]+'"$team"':/ { in_team=1; next }
        in_team && /^[[:space:]]+id:/ {
            gsub(/.*id:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_team && /^[[:space:]][[:space:]][A-Za-z]+:/ && !/^[[:space:]]+id:/ && !/^[[:space:]]+key:/ && !/^[[:space:]]+icon:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get all team names from config
get_team_names() {
    awk '
        /^teams:/ { in_teams=1; next }
        in_teams && /^[[:space:]][[:space:]][A-Z][a-zA-Z]+:/ {
            gsub(/^[[:space:]]+/, "")
            gsub(/:.*/, "")
            print
        }
        in_teams && /^[a-z]+:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get user ID from config
get_user_id() {
    awk '
        /^user:/ { in_user=1; next }
        in_user && /^[[:space:]]+id:/ {
            gsub(/.*id:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_user && /^[a-z]+:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# Get user name from config
get_user_name() {
    awk '
        /^user:/ { in_user=1; next }
        in_user && /^[[:space:]]+name:/ {
            gsub(/.*name:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_user && /^[a-z]+:/ { exit }
    ' "$CONFIG_FILE" 2>/dev/null
}

# ============================================================================
# Operation: --init
# ============================================================================

do_init() {
    md_echo ""
    md_echo "# Linear Insights Configuration Setup"
    md_echo ""
    md_echo "**Operation**: Initialize configuration from Linear API"
    md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
    md_echo ""

    if config_exists; then
        md_echo "**Warning**: config.yaml already exists at:"
        md_echo "\`$CONFIG_FILE\`"
        md_echo ""
        if [[ "$BACKUP" == "true" ]]; then
            backup_config
        else
            md_echo "*Use --backup flag to create backup before overwriting.*"
        fi
        md_echo ""
    fi

    md_echo "---"
    md_echo ""
    md_echo "## Step 1: Query Linear for Teams"
    md_echo ""
    md_echo "Execute this MCP query to get team information:"
    md_echo ""
    md_echo '```python'
    md_echo "teams_result = mcp__linear-server__list_teams()"
    md_echo '```'
    md_echo ""
    md_echo "**Expected Response Fields**:"
    md_echo "- \`id\`: Team UUID (e.g., \`9bdff6a3-f4ef-4ff7-b29a-6c4cf44371e6\`)"
    md_echo "- \`name\`: Team name (e.g., \`Omninode\`)"
    md_echo "- \`key\`: Team key prefix (e.g., \`OMNI\`)"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Step 2: Query Linear for Projects"
    md_echo ""
    md_echo "Execute this MCP query to get all projects:"
    md_echo ""
    md_echo '```python'
    md_echo "projects_result = mcp__linear-server__list_projects("
    md_echo "    member=\"me\","
    md_echo "    limit=50"
    md_echo ")"
    md_echo '```'
    md_echo ""
    md_echo "**Expected Response Fields per Project**:"
    md_echo "- \`id\`: Project UUID"
    md_echo "- \`name\`: Project name"
    md_echo "- \`state\`: Project state (Planned, In Progress, etc.)"
    md_echo "- \`lead\`: Project lead (if assigned)"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Step 3: Query Linear for Users"
    md_echo ""
    md_echo "Execute this MCP query to get user information:"
    md_echo ""
    md_echo '```python'
    md_echo "users_result = mcp__linear-server__list_users()"
    md_echo '```'
    md_echo ""
    md_echo "**Expected Response Fields per User**:"
    md_echo "- \`id\`: User UUID"
    md_echo "- \`name\`: Full name"
    md_echo "- \`email\`: Email address"
    md_echo "- \`displayName\`: Display name (username)"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Step 4: Generate Configuration"
    md_echo ""
    md_echo "After running the above queries, use this template to create \`config.yaml\`:"
    md_echo ""
    md_echo '```yaml'
    md_echo "# Linear Insights v2 Configuration"
    md_echo "# Auto-generated from Linear API"
    md_echo "# Last updated: $(date '+%Y-%m-%d')"
    md_echo ""
    md_echo 'version: "2.1"'
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# DEFAULTS"
    md_echo "# ============================================================================="
    md_echo "defaults:"
    md_echo '  project: "MVP"  # Default project shortcut'
    md_echo '  team: "Omninode"'
    md_echo '  user: "me"'
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# USER CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "# Replace with values from mcp__linear-server__list_users()"
    md_echo "user:"
    md_echo '  id: "<USER_ID>"'
    md_echo '  name: "<USER_NAME>"'
    md_echo '  email: "<USER_EMAIL>"'
    md_echo '  displayName: "<DISPLAY_NAME>"'
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# TEAM CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "# Replace with values from mcp__linear-server__list_teams()"
    md_echo "teams:"
    md_echo "  TeamName:"
    md_echo '    id: "<TEAM_ID>"'
    md_echo '    key: "<TEAM_KEY>"'
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# PROJECT CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "# Replace with values from mcp__linear-server__list_projects()"
    md_echo "projects:"
    md_echo "  ProjectShortcut:"
    md_echo '    id: "<PROJECT_ID>"'
    md_echo '    name: "<PROJECT_NAME>"'
    md_echo '    shortcuts: ["shortcut1", "shortcut2"]'
    md_echo '    status: "<PROJECT_STATE>"'
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# BACKLOG QUERY CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "backlog:"
    md_echo '  state: "Backlog"'
    md_echo "  blocked_labels:"
    md_echo '    - "blocked"'
    md_echo '    - "waiting"'
    md_echo '    - "on-hold"'
    md_echo '    - "needs-clarification"'
    md_echo '    - "dependent"'
    md_echo "  default_count: 5"
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# CACHE CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "cache:"
    md_echo "  enabled: true"
    md_echo '  directory: ".cache"'
    md_echo "  ttl:"
    md_echo "    projects: 86400    # 24 hours"
    md_echo "    teams: 86400       # 24 hours"
    md_echo "    issues: 300        # 5 minutes"
    md_echo "    users: 3600        # 1 hour"
    md_echo ""
    md_echo "# ============================================================================="
    md_echo "# OUTPUT CONFIGURATION"
    md_echo "# ============================================================================="
    md_echo "output:"
    md_echo '  deep_dive_dir: "${HOME}/Code/omni_home/omni_save"'
    md_echo '  snapshot_dir: ".cache/snapshots"'
    md_echo '  default_format: "markdown"'
    md_echo '```'
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## After Configuration"
    md_echo ""
    md_echo "Once config.yaml is created, verify with:"
    md_echo ""
    md_echo '```bash'
    md_echo "$(basename "$0") --validate"
    md_echo '```'
    md_echo ""
    md_echo "Then test with:"
    md_echo ""
    md_echo '```bash'
    md_echo "\${CLAUDE_PLUGIN_ROOT}/skills/linear-insights/suggest-work"
    md_echo '```'
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "*Configuration location: $CONFIG_FILE*"

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        python3 << PYTHON_EOF
import json
from datetime import datetime, timezone

result = {
    "operation": "init",
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "config_path": "$CONFIG_FILE",
    "config_exists": $(config_exists && echo "True" || echo "False"),
    "backup_created": $([[ "$BACKUP" == "true" ]] && config_exists && echo "True" || echo "False"),
    "mcp_queries": [
        {
            "step": 1,
            "name": "List Teams",
            "tool": "mcp__linear-server__list_teams",
            "parameters": {}
        },
        {
            "step": 2,
            "name": "List Projects",
            "tool": "mcp__linear-server__list_projects",
            "parameters": {
                "member": "me",
                "limit": 50
            }
        },
        {
            "step": 3,
            "name": "List Users",
            "tool": "mcp__linear-server__list_users",
            "parameters": {}
        }
    ],
    "next_steps": [
        "Execute the MCP queries listed above",
        "Create config.yaml using the template",
        "Run 'setup --validate' to verify",
        "Run 'suggest-work' to test"
    ]
}

print(json.dumps(result, indent=2))
PYTHON_EOF
    fi
}

# ============================================================================
# Operation: --refresh
# ============================================================================

do_refresh() {
    if ! config_exists; then
        echo "Error: Configuration file not found: $CONFIG_FILE"
        echo "Run '$(basename "$0") --init' first to create configuration."
        exit 1
    fi

    if [[ "$BACKUP" == "true" ]]; then
        backup_config
    fi

    md_echo ""
    md_echo "# Refresh Linear Insights Configuration"
    md_echo ""
    md_echo "**Operation**: Update project/team IDs from Linear"
    md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
    md_echo "**Config File**: \`$CONFIG_FILE\`"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Current Configuration"
    md_echo ""
    md_echo "### Projects"
    md_echo ""
    md_echo "| Shortcut | Name | ID |"
    md_echo "|----------|------|----|"

    get_project_shortcuts | while read -r shortcut; do
        if [[ -n "$shortcut" ]]; then
            local id=$(get_project_id "$shortcut")
            local name=$(get_project_name "$shortcut")
            md_echo "| $shortcut | ${name:-N/A} | \`${id:-N/A}\` |"
        fi
    done

    md_echo ""
    md_echo "### Teams"
    md_echo ""
    md_echo "| Name | ID |"
    md_echo "|------|----|"

    get_team_names | while read -r team; do
        if [[ -n "$team" ]]; then
            local id=$(get_team_id "$team")
            md_echo "| $team | \`${id:-N/A}\` |"
        fi
    done

    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Refresh Queries"
    md_echo ""
    md_echo "Execute these MCP queries to get updated IDs:"
    md_echo ""
    md_echo "### 1. Projects"
    md_echo ""
    md_echo '```python'
    md_echo "projects_result = mcp__linear-server__list_projects("
    md_echo "    member=\"me\","
    md_echo "    limit=50"
    md_echo ")"
    md_echo '```'
    md_echo ""
    md_echo "### 2. Teams"
    md_echo ""
    md_echo '```python'
    md_echo "teams_result = mcp__linear-server__list_teams()"
    md_echo '```'
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Refresh Instructions"
    md_echo ""
    md_echo "After running the queries above:"
    md_echo ""
    md_echo "1. Compare the returned IDs with the current configuration"
    md_echo "2. Update any changed IDs in \`config.yaml\`"
    md_echo "3. Add any new projects with appropriate shortcuts"
    md_echo "4. **Preserve** existing: shortcuts, weights, custom settings"
    md_echo "5. Run \`$(basename "$0") --validate\` to verify"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "*Only update IDs - preserve shortcuts, weights, and custom configurations.*"

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        python3 << PYTHON_EOF
import json
from datetime import datetime, timezone

result = {
    "operation": "refresh",
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "config_path": "$CONFIG_FILE",
    "backup_created": $([[ "$BACKUP" == "true" ]] && echo "True" || echo "False"),
    "current_config": {
        "projects": [
$(get_project_shortcuts | while read -r shortcut; do
    if [[ -n "$shortcut" ]]; then
        id=$(get_project_id "$shortcut")
        name=$(get_project_name "$shortcut")
        echo "            {\"shortcut\": \"$shortcut\", \"name\": \"$name\", \"id\": \"$id\"},"
    fi
done)
        ],
        "teams": [
$(get_team_names | while read -r team; do
    if [[ -n "$team" ]]; then
        id=$(get_team_id "$team")
        echo "            {\"name\": \"$team\", \"id\": \"$id\"},"
    fi
done)
        ]
    },
    "mcp_queries": [
        {
            "name": "List Projects",
            "tool": "mcp__linear-server__list_projects",
            "parameters": {"member": "me", "limit": 50}
        },
        {
            "name": "List Teams",
            "tool": "mcp__linear-server__list_teams",
            "parameters": {}
        }
    ],
    "preserve": ["shortcuts", "weights", "custom_settings", "blocked_labels"]
}

print(json.dumps(result, indent=2, default=str))
PYTHON_EOF
    fi
}

# ============================================================================
# Operation: --validate
# ============================================================================

do_validate() {
    if ! config_exists; then
        echo "Error: Configuration file not found: $CONFIG_FILE"
        echo "Run '$(basename "$0") --init' first to create configuration."
        exit 1
    fi

    md_echo ""
    md_echo "# Validate Linear Insights Configuration"
    md_echo ""
    md_echo "**Operation**: Validate config.yaml against Linear API"
    md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
    md_echo "**Config File**: \`$CONFIG_FILE\`"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Configuration Summary"
    md_echo ""

    # Count projects
    local project_count=$(get_project_shortcuts | grep -c . || echo "0")
    local team_count=$(get_team_names | grep -c . || echo "0")
    local user_id=$(get_user_id)

    md_echo "| Item | Count/Value |"
    md_echo "|------|-------------|"
    md_echo "| Projects | $project_count |"
    md_echo "| Teams | $team_count |"
    md_echo "| User ID | \`${user_id:-Not set}\` |"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Projects to Validate"
    md_echo ""
    md_echo "| Shortcut | ID | Validation Query |"
    md_echo "|----------|----|--------------------|"

    get_project_shortcuts | while read -r shortcut; do
        if [[ -n "$shortcut" ]]; then
            local id=$(get_project_id "$shortcut")
            if [[ -n "$id" ]]; then
                md_echo "| $shortcut | \`$id\` | \`mcp__linear-server__get_project(query=\"$id\")\` |"
            else
                md_echo "| $shortcut | **MISSING** | - |"
            fi
        fi
    done

    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Validation Instructions"
    md_echo ""
    md_echo "Run these MCP queries to validate each project ID exists in Linear:"
    md_echo ""
    md_echo '```python'
    md_echo "# Validate all projects"

    get_project_shortcuts | while read -r shortcut; do
        if [[ -n "$shortcut" ]]; then
            local id=$(get_project_id "$shortcut")
            if [[ -n "$id" ]]; then
                md_echo "# $shortcut"
                md_echo "result_${shortcut} = mcp__linear-server__get_project(query=\"$id\")"
                md_echo ""
            fi
        fi
    done

    md_echo '```'
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Expected Results"
    md_echo ""
    md_echo "For each query:"
    md_echo "- **Success**: Project found with matching ID"
    md_echo "- **Failure**: Project not found (ID may have changed)"
    md_echo ""
    md_echo "If any validation fails, run \`$(basename "$0") --refresh\` to update IDs."
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "## Local Configuration Check"
    md_echo ""

    # Check for required sections
    local has_version=$(grep -c "^version:" "$CONFIG_FILE" || echo "0")
    local has_projects=$(grep -c "^projects:" "$CONFIG_FILE" || echo "0")
    local has_teams=$(grep -c "^teams:" "$CONFIG_FILE" || echo "0")
    local has_cache=$(grep -c "^cache:" "$CONFIG_FILE" || echo "0")

    md_echo "| Section | Status |"
    md_echo "|---------|--------|"
    md_echo "| version | $([ "$has_version" -gt 0 ] && echo "OK" || echo "**MISSING**") |"
    md_echo "| projects | $([ "$has_projects" -gt 0 ] && echo "OK ($project_count)" || echo "**MISSING**") |"
    md_echo "| teams | $([ "$has_teams" -gt 0 ] && echo "OK ($team_count)" || echo "**MISSING**") |"
    md_echo "| cache | $([ "$has_cache" -gt 0 ] && echo "OK" || echo "**MISSING**") |"
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "*Run the validation queries above to confirm configuration matches Linear.*"

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        python3 << PYTHON_EOF
import json
from datetime import datetime, timezone

result = {
    "operation": "validate",
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "config_path": "$CONFIG_FILE",
    "summary": {
        "project_count": $project_count,
        "team_count": $team_count,
        "user_id": "$user_id" if "$user_id" else None
    },
    "local_checks": {
        "has_version": $([ "$has_version" -gt 0 ] && echo "True" || echo "False"),
        "has_projects": $([ "$has_projects" -gt 0 ] && echo "True" || echo "False"),
        "has_teams": $([ "$has_teams" -gt 0 ] && echo "True" || echo "False"),
        "has_cache": $([ "$has_cache" -gt 0 ] && echo "True" || echo "False")
    },
    "validation_queries": [
$(get_project_shortcuts | while read -r shortcut; do
    if [[ -n "$shortcut" ]]; then
        id=$(get_project_id "$shortcut")
        if [[ -n "$id" ]]; then
            echo "        {\"shortcut\": \"$shortcut\", \"id\": \"$id\", \"query\": \"mcp__linear-server__get_project(query=\\\"$id\\\")\"},"
        fi
    fi
done)
    ]
}

print(json.dumps(result, indent=2, default=str))
PYTHON_EOF
    fi
}

# ============================================================================
# Operation: --show
# ============================================================================

do_show() {
    if ! config_exists; then
        echo "Error: Configuration file not found: $CONFIG_FILE"
        echo "Run '$(basename "$0") --init' first to create configuration."
        exit 1
    fi

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        # Output JSON representation of config
        python3 << PYTHON_EOF
import json
import sys
from datetime import datetime, timezone

# Parse YAML manually (simple key-value extraction)
config = {
    "operation": "show",
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "config_path": "$CONFIG_FILE",
    "projects": [],
    "teams": [],
    "user": {}
}

# Read projects
current_section = None
current_item = None

with open("$CONFIG_FILE", "r") as f:
    lines = f.readlines()

in_projects = False
in_teams = False
in_user = False
current_project = None
current_team = None

for line in lines:
    stripped = line.rstrip()

    # Section detection
    if stripped == "projects:":
        in_projects = True
        in_teams = False
        in_user = False
        continue
    elif stripped == "teams:":
        in_projects = False
        in_teams = True
        in_user = False
        continue
    elif stripped == "user:":
        in_projects = False
        in_teams = False
        in_user = True
        continue
    elif stripped and not stripped.startswith(" ") and stripped.endswith(":"):
        in_projects = False
        in_teams = False
        in_user = False
        continue

    # Parse projects
    if in_projects and stripped.startswith("  ") and not stripped.startswith("    "):
        # New project entry
        name = stripped.strip().rstrip(":")
        if name and name[0].isupper():
            current_project = {"shortcut": name}
            config["projects"].append(current_project)
    elif in_projects and current_project and stripped.startswith("    "):
        # Project property
        if "id:" in stripped:
            val = stripped.split("id:")[-1].strip().strip('"').strip("'")
            current_project["id"] = val
        elif "name:" in stripped:
            val = stripped.split("name:")[-1].strip().strip('"').strip("'")
            current_project["name"] = val
        elif "status:" in stripped:
            val = stripped.split("status:")[-1].strip().strip('"').strip("'")
            current_project["status"] = val

    # Parse teams
    if in_teams and stripped.startswith("  ") and not stripped.startswith("    "):
        name = stripped.strip().rstrip(":")
        if name and name[0].isupper():
            current_team = {"name": name}
            config["teams"].append(current_team)
    elif in_teams and current_team and stripped.startswith("    "):
        if "id:" in stripped:
            val = stripped.split("id:")[-1].strip().strip('"').strip("'")
            current_team["id"] = val
        elif "key:" in stripped:
            val = stripped.split("key:")[-1].strip().strip('"').strip("'")
            current_team["key"] = val

    # Parse user
    if in_user and stripped.startswith("  "):
        if "id:" in stripped:
            val = stripped.split("id:")[-1].strip().strip('"').strip("'")
            config["user"]["id"] = val
        elif "name:" in stripped:
            val = stripped.split("name:")[-1].strip().strip('"').strip("'")
            config["user"]["name"] = val
        elif "email:" in stripped:
            val = stripped.split("email:")[-1].strip().strip('"').strip("'")
            config["user"]["email"] = val

print(json.dumps(config, indent=2))
PYTHON_EOF
    else
        # Markdown output
        md_echo ""
        md_echo "# Linear Insights Configuration"
        md_echo ""
        md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
        md_echo "**Config File**: \`$CONFIG_FILE\`"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## User"
        md_echo ""
        local user_id=$(get_user_id)
        local user_name=$(get_user_name)
        md_echo "| Field | Value |"
        md_echo "|-------|-------|"
        md_echo "| ID | \`${user_id:-Not set}\` |"
        md_echo "| Name | ${user_name:-Not set} |"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Teams"
        md_echo ""
        md_echo "| Name | ID | Key |"
        md_echo "|------|----|----|"

        get_team_names | while read -r team; do
            if [[ -n "$team" ]]; then
                local id=$(get_team_id "$team")
                local key=$(awk -v team="$team" '
                    /^[[:space:]]+'"$team"':/ { in_team=1; next }
                    in_team && /^[[:space:]]+key:/ {
                        gsub(/.*key:[[:space:]]*/, "")
                        gsub(/^"/, "")
                        gsub(/"$/, "")
                        print
                        exit
                    }
                    in_team && /^[[:space:]][[:space:]][A-Za-z]+:/ && !/^[[:space:]]+id:/ && !/^[[:space:]]+key:/ { exit }
                ' "$CONFIG_FILE")
                md_echo "| $team | \`${id:-N/A}\` | ${key:-N/A} |"
            fi
        done

        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Projects"
        md_echo ""
        md_echo "| Shortcut | Name | ID | Status |"
        md_echo "|----------|------|----|--------|"

        get_project_shortcuts | while read -r shortcut; do
            if [[ -n "$shortcut" ]]; then
                local id=$(get_project_id "$shortcut")
                local name=$(get_project_name "$shortcut")
                local status=$(awk -v proj="$shortcut" '
                    /^[[:space:]]+'"$shortcut"':/ { in_project=1; next }
                    in_project && /^[[:space:]]+status:/ {
                        gsub(/.*status:[[:space:]]*/, "")
                        gsub(/^"/, "")
                        gsub(/"$/, "")
                        print
                        exit
                    }
                    in_project && /^[[:space:]][[:space:]][A-Za-z]+:/ && !/^[[:space:]]+id:/ && !/^[[:space:]]+name:/ && !/^[[:space:]]+shortcuts:/ && !/^[[:space:]]+status:/ { exit }
                ' "$CONFIG_FILE")
                md_echo "| $shortcut | ${name:-N/A} | \`${id:-N/A}\` | ${status:-N/A} |"
            fi
        done

        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Cache Settings"
        md_echo ""
        local cache_enabled=$(awk '
            /^cache:/ { in_cache=1; next }
            in_cache && /^[[:space:]]+enabled:/ {
                gsub(/.*enabled:[[:space:]]*/, "")
                print
                exit
            }
            in_cache && /^[a-z]+:/ { exit }
        ' "$CONFIG_FILE")
        local cache_dir=$(awk '
            /^cache:/ { in_cache=1; next }
            in_cache && /^[[:space:]]+directory:/ {
                gsub(/.*directory:[[:space:]]*/, "")
                gsub(/^"/, "")
                gsub(/"$/, "")
                print
                exit
            }
            in_cache && /^[a-z]+:/ { exit }
        ' "$CONFIG_FILE")

        md_echo "| Setting | Value |"
        md_echo "|---------|-------|"
        md_echo "| Enabled | ${cache_enabled:-true} |"
        md_echo "| Directory | \`${cache_dir:-.cache}\` |"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "*Use \`$(basename "$0") --validate\` to verify configuration against Linear.*"
    fi
}

# ============================================================================
# Operation: --clear-cache
# ============================================================================

do_clear_cache() {
    md_echo ""
    md_echo "# Clear Linear Insights Cache"
    md_echo ""
    md_echo "**Operation**: Clear all cached data"
    md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
    md_echo ""

    local cache_file="$CACHE_DIR/linear_cache.json"
    local snapshots_dir="$CACHE_DIR/snapshots"
    local files_removed=0
    local dirs_removed=0

    # Remove cache file
    if [[ -f "$cache_file" ]]; then
        rm -f "$cache_file"
        files_removed=$((files_removed + 1))
        md_echo "Removed: \`$cache_file\`"
    fi

    # Remove snapshots directory contents
    if [[ -d "$snapshots_dir" ]]; then
        local snapshot_count=$(find "$snapshots_dir" -type f -name "*.json" 2>/dev/null | wc -l | tr -d ' ')
        if [[ "$snapshot_count" -gt 0 ]]; then
            rm -f "$snapshots_dir"/*.json 2>/dev/null || true
            files_removed=$((files_removed + snapshot_count))
            md_echo "Removed: $snapshot_count snapshot files from \`$snapshots_dir/\`"
        fi
    fi

    # Remove estimation history if it exists in cache
    local estimation_file="$CACHE_DIR/estimation_history.json"
    if [[ -f "$estimation_file" ]]; then
        rm -f "$estimation_file"
        files_removed=$((files_removed + 1))
        md_echo "Removed: \`$estimation_file\`"
    fi

    md_echo ""
    if [[ "$files_removed" -eq 0 ]]; then
        md_echo "**No cache files found to remove.**"
    else
        md_echo "**Cache cleared.** Removed $files_removed file(s)."
    fi
    md_echo ""
    md_echo "---"
    md_echo ""
    md_echo "*Next Linear queries will repopulate the cache.*"

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        python3 << PYTHON_EOF
import json
from datetime import datetime, timezone

result = {
    "operation": "clear-cache",
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "cache_dir": "$CACHE_DIR",
    "files_removed": $files_removed,
    "status": "cleared" if $files_removed > 0 else "no_files_found"
}

print(json.dumps(result, indent=2))
PYTHON_EOF
    fi
}

# ============================================================================
# Main Execution
# ============================================================================

case "$OPERATION" in
    init)
        do_init
        ;;
    refresh)
        do_refresh
        ;;
    validate)
        do_validate
        ;;
    show)
        do_show
        ;;
    clear-cache)
        do_clear_cache
        ;;
    *)
        echo "Error: Unknown operation: $OPERATION"
        exit 1
        ;;
esac
