#!/bin/bash
set -euo pipefail

# ============================================================================
# Project Status - Quick Health Dashboard
# ============================================================================
# Shows quick health dashboard for a project including progress, velocity,
# blockers, ETA, and confidence metrics.
# Reads project configuration from config.yaml (no runtime lookups).
#
# Data Sources:
#   - Configuration: config.yaml for project IDs and thresholds
#   - Query Target: Linear MCP for project issues
#   - Metrics: Velocity, backlog, blockers from Linear
# ============================================================================

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

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

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

Quick health dashboard for a project.

Arguments:
  PROJECT           Project name/shortcut (MVP, Beta, Production, etc.)
                    If omitted, uses default from config.

Options:
  --all             Show all projects overview
  --blockers        Include blocked issues detail
  --risks           Highlight risks (high priority backlog, velocity drops)
  --confidence      Show detailed confidence breakdown
  --json            Output as JSON instead of markdown
  --emit            After outputting status, serialize snapshot and emit to Kafka via onex-linear-relay
  -h, --help        Show this help

Projects Available:
  MVP              - MVP - OmniNode Platform Foundation
  Beta             - Beta - OmniNode Platform Hardening
  Production       - Production - OmniNode Platform Scale
  NodeReducer      - NodeReducer v1.0 - Contract-Driven FSM
  EventBusAlignment - Event Bus Alignment - OmniNode Platform
  PipelineOptimization - Synchronous Pipeline Optimization

Examples:
  # Quick status for default project
  $(basename "$0")

  # Status for MVP project
  $(basename "$0") MVP

  # All projects overview
  $(basename "$0") --all

  # Include blocked issues detail
  $(basename "$0") MVP --blockers

  # Highlight risks
  $(basename "$0") MVP --risks

  # Combined flags
  $(basename "$0") MVP --blockers --risks

  # JSON output
  $(basename "$0") MVP --json

  # Emit snapshot to Kafka via onex-linear-relay (produces to onex.evt.linear.snapshot.v1)
  $(basename "$0") MVP --emit

  # Combine: JSON output + emit
  $(basename "$0") MVP --json --emit

NOTE: Do NOT call POST /api/linear/snapshot directly. That endpoint is debug-only ingress.
      Use --emit to produce Linear snapshot data to Kafka via onex-linear-relay.

Health Indicators:
  The health check evaluates:
  - Velocity stability (within 10% of average)
  - ETA vs target date
  - Blocked issue count
  - High priority backlog count
  - Backlog churn ratio

Confidence Levels:
  - High:   >= 7 days data, CV <= 15%
  - Medium: 5-6 days data, CV <= 30%
  - Low:    < 5 days data OR CV > 30%

EOF
    exit 0
}

# ============================================================================
# Configuration Parsing
# ============================================================================

# 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/'$//"
}

# Parse project ID from config
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"
}

# Parse project name from config
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"
}

# Get default project from config
get_default_project() {
    awk '
        /^defaults:/ { in_defaults=1; next }
        in_defaults && /^[[:space:]]+project:/ {
            gsub(/.*project:[[:space:]]*/, "")
            gsub(/[[:space:]]*#.*$/, "")  # Remove YAML comments
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
        in_defaults && /^[a-z]+:/ { exit }
    ' "$CONFIG_FILE"
}

# Get blocked labels from config
get_blocked_labels() {
    awk '
        /^[[:space:]]+blocked_labels:/ { in_blocked=1; next }
        in_blocked && /^[[:space:]]+-/ {
            gsub(/^[[:space:]]+-[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
        }
        in_blocked && /^[[:space:]][[:space:]][a-z_]+:/ && !/^[[:space:]]+-/ { exit }
    ' "$CONFIG_FILE"
}

# Get all project shortcuts
get_all_projects() {
    awk '
        /^projects:/ { in_projects=1; next }
        in_projects && /^[[:space:]][[:space:]][A-Z][a-zA-Z]+:/ {
            gsub(/^[[:space:]]+/, "")
            gsub(/:$/, "")
            print
        }
        in_projects && /^[a-z]+:/ && !/^[[:space:]]/ { exit }
    ' "$CONFIG_FILE"
}

# Get team ID from config
get_team_id() {
    awk '
        /^teams:/ { in_teams=1; next }
        in_teams && /^[[:space:]]+[A-Za-z]+:/ { in_team=1; next }
        in_team && /^[[:space:]]+id:/ {
            gsub(/.*id:[[:space:]]*/, "")
            gsub(/^"/, "")
            gsub(/"$/, "")
            print
            exit
        }
    ' "$CONFIG_FILE"
}

# ============================================================================
# Default Values
# ============================================================================

# Check config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "Error: Configuration file not found: $CONFIG_FILE"
    echo "Run 'configure' skill first to generate configuration."
    exit 1
fi

DEFAULT_PROJECT=$(get_default_project)

PROJECT=""
SHOW_ALL=false
SHOW_BLOCKERS=false
SHOW_RISKS=false
SHOW_CONFIDENCE=false
JSON_OUTPUT=false
EMIT=false

# ============================================================================
# Parse Arguments
# ============================================================================

while [[ $# -gt 0 ]]; do
    case $1 in
        --all)
            SHOW_ALL=true
            shift
            ;;
        --blockers)
            SHOW_BLOCKERS=true
            shift
            ;;
        --risks)
            SHOW_RISKS=true
            shift
            ;;
        --confidence)
            SHOW_CONFIDENCE=true
            shift
            ;;
        --json)
            JSON_OUTPUT=true
            shift
            ;;
        --emit)
            EMIT=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        -*)
            echo "Error: Unknown option: $1"
            usage
            ;;
        *)
            # Positional argument - treat as project name
            if [[ -z "$PROJECT" ]]; then
                PROJECT="$1"
            else
                echo "Error: Multiple project names specified"
                usage
            fi
            shift
            ;;
    esac
done

# Use default project if not specified and not showing all
if [[ -z "$PROJECT" && "$SHOW_ALL" == "false" ]]; then
    PROJECT="$DEFAULT_PROJECT"
fi

# Validate project exists in config (unless showing all)
if [[ "$SHOW_ALL" == "false" ]]; then
    PROJECT_ID=$(get_project_id "$PROJECT")
    if [[ -z "$PROJECT_ID" ]]; then
        echo "Error: Project '$PROJECT' not found in configuration."
        echo ""
        echo "Available projects:"
        get_all_projects | while read -r proj; do
            echo "  - $proj"
        done
        exit 1
    fi
    PROJECT_NAME=$(get_project_name "$PROJECT")
    PROJECT_NAME=${PROJECT_NAME:-$PROJECT}
fi

# Get blocked labels
BLOCKED_LABELS=$(get_blocked_labels)
TEAM_ID=$(get_team_id)

# ============================================================================
# Output Generation Functions
# ============================================================================

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

# Generate blocked labels JSON array
generate_blocked_labels_json() {
    local first=true
    echo -n "["
    echo "$BLOCKED_LABELS" | while read -r label; do
        if [[ -n "$label" ]]; then
            if [[ "$first" == "true" ]]; then
                echo -n "\"$label\""
                first=false
            else
                echo -n ", \"$label\""
            fi
        fi
    done
    echo -n "]"
}

# ============================================================================
# Single Project Status Output
# ============================================================================

output_single_project_status() {
    local project="$1"
    local project_id="$2"
    local project_name="$3"

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

# Add lib directory to path
sys.path.insert(0, "$SCRIPT_DIR")
from lib.velocity_calculator import (
    ConfidenceLevel,
    calculate_churn_ratio,
    calculate_adjusted_eta
)

result = {
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "project": {
        "shortcut": "$project",
        "name": "$project_name",
        "id": "$project_id"
    },
    "flags": {
        "show_blockers": $( [[ "$SHOW_BLOCKERS" == "true" ]] && echo "True" || echo "False" ),
        "show_risks": $( [[ "$SHOW_RISKS" == "true" ]] && echo "True" || echo "False" ),
        "show_confidence": $( [[ "$SHOW_CONFIDENCE" == "true" ]] && echo "True" || echo "False" )
    },
    "mcp_queries": {
        "description": "Execute these queries to populate the status dashboard",
        "queries": [
            {
                "purpose": "Get all project issues for progress calculation",
                "tool": "mcp__linear-server__list_issues",
                "parameters": {
                    "project": "$project_id",
                    "limit": 500
                }
            },
            {
                "purpose": "Get completed issues (last 7 days) for velocity",
                "tool": "mcp__linear-server__list_issues",
                "parameters": {
                    "project": "$project_id",
                    "state": "Done",
                    "limit": 100
                },
                "note": "Filter results to last 7 days by completedAt field"
            },
            {
                "purpose": "Get backlog issues for remaining work",
                "tool": "mcp__linear-server__list_issues",
                "parameters": {
                    "project": "$project_id",
                    "state": "Backlog",
                    "limit": 200
                }
            },
            {
                "purpose": "Get in-progress issues",
                "tool": "mcp__linear-server__list_issues",
                "parameters": {
                    "project": "$project_id",
                    "state": "In Progress",
                    "limit": 50
                }
            }
        ]
    },
    "calculations": {
        "progress": {
            "formula": "(completed_issues / total_issues) * 100",
            "status_rules": {
                "on_track": "progress >= expected_progress_by_date",
                "at_risk": "progress < expected_progress_by_date - 10%",
                "behind": "progress < expected_progress_by_date - 20%"
            }
        },
        "velocity": {
            "formula": "issues_completed_last_7_days / 7",
            "stability_threshold": "within 10% of average = stable"
        },
        "blockers": {
            "detection": "issues with labels: $(echo "$BLOCKED_LABELS" | tr '\n' ',' | sed 's/,$//')",
            "status_rules": {
                "ok": "0 blocked issues",
                "attention": "1-2 blocked issues",
                "critical": ">2 blocked issues"
            }
        },
        "eta": {
            "formula": "remaining_issues / velocity",
            "confidence_levels": {
                "high": ">= 7 days data AND CV <= 15%",
                "medium": "5-6 days data AND CV <= 30%",
                "low": "< 5 days data OR CV > 30%"
            }
        },
        "churn": {
            "formula": "(issues_added - issues_completed) / issues_completed",
            "threshold": "< 20% = healthy"
        }
    },
    "health_indicators": {
        "velocity_stable": {
            "check": "current_velocity within 10% of average_velocity",
            "pass": True,
            "fail": False
        },
        "eta_before_target": {
            "check": "calculated_eta <= target_date",
            "pass": True,
            "fail": False
        },
        "no_blockers": {
            "check": "blocked_issue_count == 0",
            "pass": True,
            "fail": False
        },
        "low_high_priority_backlog": {
            "check": "urgent_and_high_priority_backlog < 5",
            "pass": True,
            "fail": False
        },
        "healthy_churn": {
            "check": "churn_ratio < 20%",
            "pass": True,
            "fail": False
        }
    },
    "blocked_labels": $(generate_blocked_labels_json),
    "output_format": {
        "quick_stats_table": ["Progress", "Velocity", "Blockers", "ETA", "Confidence"],
        "health_checklist": ["velocity_stable", "eta_before_target", "no_blockers", "low_high_priority_backlog", "healthy_churn"]
    },
    "metrics_calculator": {
        "description": "Use these functions after fetching data to calculate metrics",
        "functions": {
            "confidence_level": {
                "function": "ConfidenceLevel.from_metrics(days_analyzed, cv, churn_ratio)",
                "parameters": {
                    "days_analyzed": "Number of days of snapshot data",
                    "cv": "Coefficient of variation (std_dev / mean velocity)",
                    "churn_ratio": "Backlog churn ratio (issues_added - issues_completed) / issues_completed"
                },
                "returns": "ConfidenceLevel.HIGH, MEDIUM, or LOW"
            },
            "churn_ratio": {
                "function": "calculate_churn_ratio(issues_added, issues_completed)",
                "example": "calculate_churn_ratio(15, 20)  # returns -0.25 (shrinking)"
            },
            "adjusted_eta": {
                "function": "calculate_adjusted_eta(remaining, velocity, churn_ratio)",
                "example": "calculate_adjusted_eta(50, 5.0, 0.15)  # returns {base: 10, adjusted: 11.5}"
            }
        },
        "usage_example": '''
# After fetching Linear data:
from lib.velocity_calculator import ConfidenceLevel, calculate_churn_ratio, calculate_adjusted_eta

# Calculate churn from last 7 days
churn = calculate_churn_ratio(issues_added=12, issues_completed=15)  # -0.2 = shrinking

# Calculate ETA with churn adjustment
eta = calculate_adjusted_eta(remaining=30, velocity=5.0, churn_ratio=churn)
# Returns: {base_eta_days: 6.0, adjusted_eta_days: 5.4, ...}

# Determine confidence level
# days_analyzed = number of daily snapshots used
# cv = std_dev(daily_velocities) / mean(daily_velocities)
confidence = ConfidenceLevel.from_metrics(days_analyzed=7, cv=0.12, churn_ratio=churn)
# Returns: ConfidenceLevel.HIGH
'''
    },
    "sample_calculations": {
        "description": "Example calculations to perform after MCP queries return",
        "steps": [
            "1. Count total issues and completed issues from query 1",
            "2. Count issues completed in last 7 days from query 2 (filter by completedAt)",
            "3. Calculate velocity = completed_7_days / 7",
            "4. Count issues added to backlog in last 7 days (filter by createdAt)",
            "5. churn_ratio = calculate_churn_ratio(added_7_days, completed_7_days)",
            "6. remaining = total_issues - completed_issues",
            "7. eta_result = calculate_adjusted_eta(remaining, velocity, churn_ratio)",
            "8. confidence = ConfidenceLevel.from_metrics(7, cv, churn_ratio)"
        ]
    }
}

# Add blockers section if requested
if $( [[ "$SHOW_BLOCKERS" == "true" ]] && echo "True" || echo "False" ):
    result["blockers_detail"] = {
        "query": {
            "description": "Get blocked issues with duration calculation",
            "tool": "mcp__linear-server__list_issues",
            "parameters": {
                "project": "$project_id",
                "limit": 100
            },
            "filter": "labels contains any of: $(echo "$BLOCKED_LABELS" | tr '\n' ',' | sed 's/,$//')"
        },
        "output_fields": ["issue_id", "title", "blocked_since", "days_blocked", "downstream_impact"]
    }

# Add risks section if requested
if $( [[ "$SHOW_RISKS" == "true" ]] && echo "True" || echo "False" ):
    result["risks_detail"] = {
        "checks": [
            {
                "name": "High Priority Backlog",
                "query": "Count issues in backlog with priority Urgent or High",
                "threshold": "> 5 = risk"
            },
            {
                "name": "Velocity Drop",
                "calculation": "Compare last 7 days velocity to previous 7 days",
                "threshold": "> 30% drop = risk"
            },
            {
                "name": "ETA vs Target",
                "calculation": "Compare calculated ETA to project target_date",
                "threshold": "ETA > target_date = risk"
            },
            {
                "name": "High Churn",
                "calculation": "churn_ratio over last 7 days",
                "threshold": "> 20% = risk"
            }
        ]
    }

# Add confidence breakdown if requested
if $( [[ "$SHOW_CONFIDENCE" == "true" ]] && echo "True" || echo "False" ):
    result["confidence_detail"] = {
        "description": "Detailed breakdown of confidence level calculation",
        "criteria": {
            "HIGH": {
                "days_analyzed": ">= 7 days of snapshot data",
                "cv": "<= 15% coefficient of variation",
                "churn": "No automatic downgrade"
            },
            "MEDIUM": {
                "days_analyzed": "5-6 days of snapshot data",
                "cv": "<= 30% coefficient of variation",
                "churn": "OR: HIGH criteria with churn > 20% (downgraded)"
            },
            "LOW": {
                "days_analyzed": "< 5 days of snapshot data",
                "cv": "> 30% coefficient of variation",
                "churn": "OR: MEDIUM criteria with churn > 20% (downgraded)"
            }
        },
        "metrics_needed": {
            "days_analyzed": {
                "source": "Count of daily snapshots in analysis period",
                "how_to_get": "Count unique dates with velocity data"
            },
            "cv": {
                "source": "Velocity variability",
                "how_to_get": "std_dev(daily_velocities) / mean(daily_velocities)",
                "interpretation": "Lower is better - indicates predictability"
            },
            "churn_ratio": {
                "source": "Backlog stability",
                "how_to_get": "calculate_churn_ratio(issues_added, issues_completed)",
                "interpretation": {
                    "negative": "Backlog shrinking (good)",
                    "0-20%": "Normal growth",
                    ">20%": "High churn (downgrades confidence)"
                }
            }
        },
        "calculation_example": '''
# Example: 7 days of data, velocities: [4, 6, 5, 7, 5, 6, 5]
days_analyzed = 7
mean_velocity = 5.43
std_dev = 0.98
cv = std_dev / mean_velocity  # 0.18 (18%)

# With low churn
churn = calculate_churn_ratio(issues_added=10, issues_completed=12)  # -0.17

# Result: MEDIUM confidence
# - days_analyzed >= 7: PASS
# - cv <= 15%: FAIL (18% > 15%)
# - Falls back to MEDIUM criteria: cv <= 30%: PASS
confidence = ConfidenceLevel.from_metrics(7, 0.18, -0.17)
# Returns: ConfidenceLevel.MEDIUM
''',
        "recommendations_by_level": {
            "HIGH": "ETA predictions are reliable. Use for planning.",
            "MEDIUM": "ETA predictions have moderate uncertainty. Add buffer time.",
            "LOW": "ETA predictions are unreliable. Gather more data before committing."
        }
    }

print(json.dumps(result, indent=2))
PYTHON_EOF
    else
        # Markdown output
        md_echo ""
        md_echo "# Project Status: $project"
        md_echo ""
        md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
        md_echo "**Project**: $project_name"
        md_echo "**Project ID**: \`$project_id\`"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## MCP Queries Required"
        md_echo ""
        md_echo "Execute these queries to populate the dashboard:"
        md_echo ""
        md_echo "### 1. All Project Issues (Progress)"
        md_echo ""
        md_echo '```python'
        md_echo "mcp__linear-server__list_issues("
        md_echo "    project=\"$project_id\","
        md_echo "    limit=500"
        md_echo ")"
        md_echo '```'
        md_echo ""
        md_echo "### 2. Completed Issues (Velocity)"
        md_echo ""
        md_echo '```python'
        md_echo "mcp__linear-server__list_issues("
        md_echo "    project=\"$project_id\","
        md_echo "    state=\"Done\","
        md_echo "    limit=100"
        md_echo ")"
        md_echo '```'
        md_echo ""
        md_echo "**Note**: Filter results to last 7 days by \`completedAt\` field."
        md_echo ""
        md_echo "### 3. Backlog Issues (Remaining Work)"
        md_echo ""
        md_echo '```python'
        md_echo "mcp__linear-server__list_issues("
        md_echo "    project=\"$project_id\","
        md_echo "    state=\"Backlog\","
        md_echo "    limit=200"
        md_echo ")"
        md_echo '```'
        md_echo ""
        md_echo "### 4. In Progress Issues"
        md_echo ""
        md_echo '```python'
        md_echo "mcp__linear-server__list_issues("
        md_echo "    project=\"$project_id\","
        md_echo "    state=\"In Progress\","
        md_echo "    limit=50"
        md_echo ")"
        md_echo '```'
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Quick Stats (Template)"
        md_echo ""
        md_echo "Populate this table from query results:"
        md_echo ""
        md_echo "| Metric | Value | Status |"
        md_echo "|--------|-------|--------|"
        md_echo "| Progress | {completed}/{total} ({percent}%) | {On Track/At Risk/Behind} |"
        md_echo "| Velocity | {N} issues/day | {Stable/Declining/Improving} |"
        md_echo "| Blockers | {count} | {OK/Attention Needed/Critical} |"
        md_echo "| Churn Ratio | {ratio}% | {Healthy/High} |"
        md_echo "| Base ETA | {N} days | {date} |"
        md_echo "| Adjusted ETA | {N} days | (churn-adjusted) |"
        md_echo "| Confidence | {High/Medium/Low} | {N} days data, CV={X}% |"
        md_echo ""
        md_echo "### Calculation Rules"
        md_echo ""
        md_echo "**Progress Status**:"
        md_echo "- On Track: progress >= expected by date"
        md_echo "- At Risk: progress < expected - 10%"
        md_echo "- Behind: progress < expected - 20%"
        md_echo ""
        md_echo "**Velocity Status**:"
        md_echo "- Stable: within 10% of 30-day average"
        md_echo "- Declining: > 10% below average"
        md_echo "- Improving: > 10% above average"
        md_echo ""
        md_echo "**Blocker Status**:"
        md_echo "- OK: 0 blocked issues"
        md_echo "- Attention Needed: 1-2 blocked issues"
        md_echo "- Critical: > 2 blocked issues"
        md_echo ""
        md_echo "**Confidence Level**:"
        md_echo "- High: >= 7 days data AND CV <= 15%"
        md_echo "- Medium: 5-6 days data AND CV <= 30%"
        md_echo "- Low: < 5 days data OR CV > 30%"
        md_echo "- Note: Churn > 20% downgrades confidence by one level"
        md_echo ""
        md_echo "**Churn Ratio**:"
        md_echo "- Healthy: < 20% (or negative = backlog shrinking)"
        md_echo "- High: >= 20% (impacts confidence and ETA)"
        md_echo ""
        md_echo "**ETA Adjustment**:"
        md_echo "- Negative churn: ETA reduced up to 10% (cautious)"
        md_echo "- 0-20% churn: ETA inflated proportionally"
        md_echo "- > 20% churn: ETA inflated + confidence downgraded"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Metrics Calculator Functions"
        md_echo ""
        md_echo "Use these functions from \`lib/velocity_calculator.py\` after fetching data:"
        md_echo ""
        md_echo '```python'
        md_echo "import sys"
        md_echo "sys.path.insert(0, '$SCRIPT_DIR')"
        md_echo "from lib.velocity_calculator import ("
        md_echo "    ConfidenceLevel,"
        md_echo "    calculate_churn_ratio,"
        md_echo "    calculate_adjusted_eta"
        md_echo ")"
        md_echo ""
        md_echo "# Calculate churn ratio"
        md_echo "churn = calculate_churn_ratio(issues_added=15, issues_completed=20)"
        md_echo "# Returns: -0.25 (negative = backlog shrinking)"
        md_echo ""
        md_echo "# Calculate adjusted ETA"
        md_echo "eta = calculate_adjusted_eta(remaining=50, velocity=5.0, churn_ratio=churn)"
        md_echo "# Returns: {"
        md_echo "#   'base_eta_days': 10.0,"
        md_echo "#   'adjusted_eta_days': 9.0,  # reduced due to negative churn"
        md_echo "#   'churn_ratio': -0.25,"
        md_echo "#   'adjustment_applied': -0.10,  # capped at -10%"
        md_echo "#   'confidence_downgrade': False"
        md_echo "# }"
        md_echo ""
        md_echo "# Determine confidence level"
        md_echo "confidence = ConfidenceLevel.from_metrics("
        md_echo "    days_analyzed=7,"
        md_echo "    cv=0.12,  # coefficient of variation"
        md_echo "    churn_ratio=-0.25"
        md_echo ")"
        md_echo "# Returns: ConfidenceLevel.HIGH"
        md_echo '```'
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Health Indicators (Template)"
        md_echo ""
        md_echo "Check each indicator based on query results:"
        md_echo ""
        md_echo "- [ ] Velocity stable (within 10% of average)"
        md_echo "- [ ] ETA before target date"
        md_echo "- [ ] Blocked issues = 0"
        md_echo "- [ ] High priority backlog < 5"
        md_echo "- [ ] Churn ratio < 20%"
        md_echo ""
        md_echo "### Blocked Label Detection"
        md_echo ""
        md_echo "Issues with any of these labels are considered blocked:"
        md_echo ""
        echo "$BLOCKED_LABELS" | while read -r label; do
            if [[ -n "$label" ]]; then
                md_echo "- \`$label\`"
            fi
        done
        md_echo ""

        # Blockers detail section
        if [[ "$SHOW_BLOCKERS" == "true" ]]; then
            md_echo "---"
            md_echo ""
            md_echo "## Blocked Issues Detail"
            md_echo ""
            md_echo "Query for blocked issues:"
            md_echo ""
            md_echo '```python'
            md_echo "# Get all issues, then filter by blocked labels"
            md_echo "issues = mcp__linear-server__list_issues("
            md_echo "    project=\"$project_id\","
            md_echo "    limit=100"
            md_echo ")"
            md_echo ""
            md_echo "# Filter to issues with blocked labels"
            md_echo "blocked_labels = $(generate_blocked_labels_json)"
            md_echo "blocked_issues = [i for i in issues if any(l in i.labels for l in blocked_labels)]"
            md_echo '```'
            md_echo ""
            md_echo "### Expected Output Format"
            md_echo ""
            md_echo "| # | Issue | Title | Blocked Since | Days Blocked | Downstream Impact |"
            md_echo "|---|-------|-------|---------------|--------------|-------------------|"
            md_echo "| 1 | OMNI-XXX | Issue title... | 2025-12-12 | 2 days | 3 issues |"
            md_echo "| 2 | OMNI-YYY | Another issue... | 2025-12-13 | 1 day | 1 issue |"
            md_echo ""
            md_echo "**Downstream Impact**: Count of issues that depend on or are blocked by this issue."
            md_echo ""
        fi

        # Risks detail section
        if [[ "$SHOW_RISKS" == "true" ]]; then
            md_echo "---"
            md_echo ""
            md_echo "## Risk Assessment"
            md_echo ""
            md_echo "Evaluate these risk factors:"
            md_echo ""
            md_echo "### 1. High Priority Backlog"
            md_echo ""
            md_echo "Count issues in Backlog with priority Urgent or High:"
            md_echo ""
            md_echo '```python'
            md_echo "backlog_issues = mcp__linear-server__list_issues("
            md_echo "    project=\"$project_id\","
            md_echo "    state=\"Backlog\","
            md_echo "    limit=100"
            md_echo ")"
            md_echo "high_priority_count = len([i for i in backlog_issues if i.priority in [1, 2]])"
            md_echo '```'
            md_echo ""
            md_echo "| Count | Risk Level |"
            md_echo "|-------|------------|"
            md_echo "| 0-2   | Low        |"
            md_echo "| 3-5   | Medium     |"
            md_echo "| > 5   | High       |"
            md_echo ""
            md_echo "### 2. Velocity Drop"
            md_echo ""
            md_echo "Compare last 7 days velocity to previous 7 days:"
            md_echo ""
            md_echo "| Drop % | Risk Level |"
            md_echo "|--------|------------|"
            md_echo "| < 10%  | Low        |"
            md_echo "| 10-30% | Medium     |"
            md_echo "| > 30%  | High       |"
            md_echo ""
            md_echo "### 3. ETA vs Target Date"
            md_echo ""
            md_echo "Compare calculated ETA to project target date:"
            md_echo ""
            md_echo "| Comparison | Risk Level |"
            md_echo "|------------|------------|"
            md_echo "| ETA before target | Low |"
            md_echo "| ETA within 1 week of target | Medium |"
            md_echo "| ETA after target | High |"
            md_echo ""
            md_echo "### 4. Backlog Churn"
            md_echo ""
            md_echo "Calculate: (issues_added - issues_completed) / issues_completed"
            md_echo ""
            md_echo "| Churn Ratio | Risk Level |"
            md_echo "|-------------|------------|"
            md_echo "| < 0% (shrinking) | Low |"
            md_echo "| 0-20% | Medium |"
            md_echo "| > 20% | High |"
            md_echo ""
        fi

        # Confidence breakdown section
        if [[ "$SHOW_CONFIDENCE" == "true" ]]; then
            md_echo "---"
            md_echo ""
            md_echo "## Confidence Level Breakdown"
            md_echo ""
            md_echo "Detailed breakdown of how confidence level is determined."
            md_echo ""
            md_echo "### Confidence Level Criteria"
            md_echo ""
            md_echo "| Level | Days Analyzed | CV (Coefficient of Variation) | Churn Impact |"
            md_echo "|-------|---------------|-------------------------------|--------------|"
            md_echo "| HIGH | >= 7 days | <= 15% | None |"
            md_echo "| MEDIUM | 5-6 days | <= 30% | OR: HIGH with churn > 20% |"
            md_echo "| LOW | < 5 days | > 30% | OR: MEDIUM with churn > 20% |"
            md_echo ""
            md_echo "### Metrics Required"
            md_echo ""
            md_echo "1. **days_analyzed**: Number of daily snapshots with velocity data"
            md_echo "   - Count unique dates where issues were completed"
            md_echo "   - More days = more stable average"
            md_echo ""
            md_echo "2. **cv (Coefficient of Variation)**: Velocity variability"
            md_echo "   - Formula: \`std_dev(daily_velocities) / mean(daily_velocities)\`"
            md_echo "   - Lower is better (more predictable)"
            md_echo "   - Example: CV of 0.15 means velocity varies by +/- 15% around mean"
            md_echo ""
            md_echo "3. **churn_ratio**: Backlog stability"
            md_echo "   - Formula: \`(issues_added - issues_completed) / issues_completed\`"
            md_echo "   - Negative = backlog shrinking (good)"
            md_echo "   - > 20% = high churn (downgrades confidence)"
            md_echo ""
            md_echo "### Calculation Example"
            md_echo ""
            md_echo '```python'
            md_echo "# Given 7 days of velocity data: [4, 6, 5, 7, 5, 6, 5]"
            md_echo "import statistics"
            md_echo ""
            md_echo "daily_velocities = [4, 6, 5, 7, 5, 6, 5]"
            md_echo "days_analyzed = len(daily_velocities)  # 7"
            md_echo "mean_velocity = statistics.mean(daily_velocities)  # 5.43"
            md_echo "std_dev = statistics.stdev(daily_velocities)  # 0.98"
            md_echo "cv = std_dev / mean_velocity  # 0.18 (18%)"
            md_echo ""
            md_echo "# Churn calculation"
            md_echo "issues_added = 10"
            md_echo "issues_completed = 12"
            md_echo "churn = (10 - 12) / 12  # -0.17 (shrinking)"
            md_echo ""
            md_echo "# Confidence determination:"
            md_echo "# - days_analyzed >= 7: PASS"
            md_echo "# - cv <= 15%: FAIL (18% > 15%)"
            md_echo "# - Check MEDIUM: cv <= 30%: PASS"
            md_echo "# - churn > 20%: No (no downgrade)"
            md_echo "# Result: MEDIUM confidence"
            md_echo '```'
            md_echo ""
            md_echo "### Recommendations by Level"
            md_echo ""
            md_echo "| Level | Interpretation | Recommendation |"
            md_echo "|-------|----------------|----------------|"
            md_echo "| HIGH | ETA is reliable | Use for planning and commitments |"
            md_echo "| MEDIUM | Moderate uncertainty | Add 20-30% buffer to ETA |"
            md_echo "| LOW | High uncertainty | Gather more data before committing |"
            md_echo ""
            md_echo "### Impact on ETA"
            md_echo ""
            md_echo "Churn ratio affects ETA adjustment:"
            md_echo ""
            md_echo "| Churn Range | ETA Adjustment |"
            md_echo "|-------------|----------------|"
            md_echo "| < 0% | Reduce ETA by up to 10% (cautious) |"
            md_echo "| 0% - 20% | Increase ETA proportionally |"
            md_echo "| > 20% | Increase ETA + downgrade confidence |"
            md_echo ""
        fi

        md_echo "---"
        md_echo ""
        md_echo "## Action Items (Template)"
        md_echo ""
        md_echo "Based on status, generate action items:"
        md_echo ""
        md_echo "1. **If blockers > 0**: List blocked issues with resolution owners"
        md_echo "2. **If high priority backlog > 5**: Prioritize or reassign urgent items"
        md_echo "3. **If ETA > target**: Identify scope cuts or resource additions"
        md_echo "4. **If velocity declining**: Investigate impediments"
        md_echo "5. **If churn > 20%**: Review scope stability with stakeholders"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "*Script generated by linear-insights project-status skill*"
    fi
}

# ============================================================================
# All Projects Overview Output
# ============================================================================

output_all_projects_status() {
    local projects
    projects=$(get_all_projects)

    if [[ "$JSON_OUTPUT" == "true" ]]; then
        # JSON output for all projects
        python3 << PYTHON_EOF
import json
from datetime import datetime, timezone

projects_list = """$projects""".strip().split('\n')

result = {
    "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "mode": "all_projects_overview",
    "projects": []
}

for proj in projects_list:
    if proj.strip():
        result["projects"].append({
            "shortcut": proj.strip(),
            "query_instruction": f"Run project-status {proj.strip()} for detailed status"
        })

result["mcp_queries"] = {
    "description": "Execute these queries to get overview data for all projects",
    "queries": [
        {
            "purpose": "Get all projects with issue counts",
            "tool": "mcp__linear-server__list_projects",
            "parameters": {
                "member": "me",
                "limit": 50
            }
        }
    ]
}

result["output_format"] = {
    "table_columns": ["Project", "Progress", "Velocity", "Blockers", "ETA", "Status"],
    "status_values": ["On Track", "At Risk", "Behind", "Complete"]
}

print(json.dumps(result, indent=2))
PYTHON_EOF
    else
        # Markdown output
        md_echo ""
        md_echo "# All Projects Overview"
        md_echo ""
        md_echo "**Generated**: $(date '+%Y-%m-%d %H:%M:%S')"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## MCP Query"
        md_echo ""
        md_echo "Get all projects with their status:"
        md_echo ""
        md_echo '```python'
        md_echo "mcp__linear-server__list_projects("
        md_echo "    member=\"me\","
        md_echo "    limit=50"
        md_echo ")"
        md_echo '```'
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Projects Table (Template)"
        md_echo ""
        md_echo "Populate from query results:"
        md_echo ""
        md_echo "| Project | Progress | Velocity | Blockers | ETA | Status |"
        md_echo "|---------|----------|----------|----------|-----|--------|"

        echo "$projects" | while read -r proj; do
            if [[ -n "$proj" ]]; then
                proj_name=$(get_project_name "$proj")
                md_echo "| $proj | -/-  (-%) | - issues/day | - | - | - |"
            fi
        done

        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Per-Project Queries"
        md_echo ""
        md_echo "For detailed status of each project, run:"
        md_echo ""

        echo "$projects" | while read -r proj; do
            if [[ -n "$proj" ]]; then
                md_echo "- \`project-status $proj\`"
            fi
        done

        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "## Summary Indicators"
        md_echo ""
        md_echo "After populating the table, summarize:"
        md_echo ""
        md_echo "- **Projects On Track**: {count}"
        md_echo "- **Projects At Risk**: {count}"
        md_echo "- **Projects Behind**: {count}"
        md_echo "- **Total Blockers**: {sum of all project blockers}"
        md_echo "- **Highest Risk Project**: {project with most issues}"
        md_echo ""
        md_echo "---"
        md_echo ""
        md_echo "*Script generated by linear-insights project-status skill*"
    fi
}

# ============================================================================
# Kafka Emission (--emit flag)
# ============================================================================
#
# Serializes a workstream snapshot JSON and calls onex-linear-relay to produce
# it to onex.evt.linear.snapshot.v1.
#
# IMPORTANT: Do NOT call POST /api/linear/snapshot directly.
#            That endpoint is debug-only ingress.
#            This function is the only correct production path.
# ============================================================================

emit_snapshot() {
    local project="$1"
    local project_name="$2"
    local timestamp
    timestamp=$(date -u +%Y%m%dT%H%M%SZ)
    local snapshot_file="/tmp/linear-snapshot-${timestamp}.json"

    # Build minimal workstream snapshot JSON.
    # The agent executing this skill is expected to have already fetched
    # Linear data via MCP and can pass richer workstream data.
    # This baseline snapshot includes project identity and generation metadata.
    python3 - <<PYEOF
import json, sys
from datetime import datetime, timezone

# Collect all project shortcuts for the snapshot's workstreams list.
# In single-project mode, emit the one project; in --all mode, emit all.
projects_raw = """$( [[ "$SHOW_ALL" == "true" ]] && get_all_projects || echo "$project" )"""
workstreams = [p.strip() for p in projects_raw.strip().splitlines() if p.strip()]

snapshot = {
    "workstreams": workstreams,
    "project": "$project_name",
    "project_shortcut": "$project",
    "source": "project-status",
    "generated_at": datetime.now(timezone.utc).isoformat(),
}
with open("$snapshot_file", "w", encoding="utf-8") as f:
    json.dump(snapshot, f)
PYEOF

    if [[ ! -f "$snapshot_file" ]]; then
        echo "[project-status] ERROR: Failed to create snapshot file at $snapshot_file" >&2
        return 1
    fi

    echo "[project-status] Emitting snapshot to onex.evt.linear.snapshot.v1 ..."
    if command -v onex-linear-relay &>/dev/null; then
        onex-linear-relay emit --snapshot-file "$snapshot_file"
        # Clean up tmp file after successful relay invocation (relay is non-blocking,
        # exit 0 regardless of Kafka reachability — file no longer needed after this point).
        rm -f "$snapshot_file"
    else
        echo "[project-status] WARNING: onex-linear-relay not found in PATH." >&2
        echo "[project-status] Install omnibase_infra package or add its .venv/bin to PATH." >&2
        echo "[project-status] Snapshot file retained at: $snapshot_file" >&2
        return 1
    fi
}

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

if [[ "$SHOW_ALL" == "true" ]]; then
    output_all_projects_status
else
    output_single_project_status "$PROJECT" "$PROJECT_ID" "$PROJECT_NAME"
fi

# Emit snapshot to Kafka if --emit flag was set.
if [[ "$EMIT" == "true" ]]; then
    if [[ "$SHOW_ALL" == "true" ]]; then
        emit_snapshot "all" "All Projects"
    else
        emit_snapshot "$PROJECT" "$PROJECT_NAME"
    fi
fi
