import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { areSkillsInstalled } from "./config.js";
export const SKILLS_VERSION = "3";
const VERSION_MARKER_PREFIX = "<!-- skills-version:";
/**
 * Legacy workflow prompt used by Codex, Cursor, Windsurf agents.
 * Claude Code skills use the newer SKILL_DEFINITIONS content instead.
 */
export const HARMONY_WORKFLOW_PROMPT = `# Harmony Card Workflow

Start work on a Harmony card. Card reference: $ARGUMENTS

## 1. Find & Fetch Card

Parse the reference and fetch the card:
- \`#42\` or \`42\` → \`harmony_get_card_by_short_id\` with \`shortId: 42\`
- UUID → \`harmony_get_card\` with \`cardId\`
- Name/text → \`harmony_search_cards\` with \`query\`

## 2. Get Board State

Call \`harmony_get_board\` to get columns and labels. From the response:
- Find the "In Progress" (or "Progress") column ID
- Find the "agent" label ID

## 3. Setup Card for Work

Execute these in sequence:
1. \`harmony_move_card\` → Move to "In Progress" column
2. \`harmony_add_label_to_card\` → Add "agent" label
3. \`harmony_start_agent_session\`:
   - \`cardId\`: Card UUID
   - \`agentIdentifier\`: Your agent identifier
   - \`agentName\`: Your agent name
   - \`currentTask\`: "Analyzing card requirements"

## 4. Generate Work Prompt

Call \`harmony_generate_prompt\` with:
- \`cardId\` or \`shortId\` (+ \`projectId\` if using shortId)
- \`variant\`: Select based on task:
  - \`"execute"\` (default) → Clear tasks, bug fixes, well-defined work
  - \`"analysis"\` → Complex features, unclear requirements
  - \`"draft"\` → Medium complexity, want feedback first

The generated prompt provides role framing, focus areas, subtasks, linked cards, and suggested outputs.

## 5. Display Card Summary

Show the user: Card title, short ID, role, priority, labels, due date, description, and subtasks.

## 6. Implement Solution

Work on the card following the generated prompt's guidance. Update progress at milestones:
- \`harmony_update_agent_progress\` with \`progressPercent\` (0-100), \`currentTask\`, \`status\`, \`blockers\`

**Progress checkpoints:** 20% (exploration), 50% (implementation), 80% (testing), 100% (done)

## 7. Complete Work

When finished:
1. \`harmony_end_agent_session\` with \`status: "completed"\`, \`progressPercent: 100\`
2. \`harmony_move_card\` to "Review" column
3. Summarize accomplishments

If pausing: \`harmony_end_agent_session\` with \`status: "paused"\`

## Key Tools Reference

**Cards:** \`harmony_get_card\`, \`harmony_get_card_by_short_id\`, \`harmony_search_cards\`, \`harmony_create_card\`, \`harmony_update_card\`, \`harmony_move_card\`, \`harmony_delete_card\`, \`harmony_assign_card\`

**Subtasks:** \`harmony_create_subtask\`, \`harmony_toggle_subtask\`, \`harmony_delete_subtask\`

**Labels:** \`harmony_add_label_to_card\`, \`harmony_remove_label_from_card\`, \`harmony_create_label\`

**Links:** \`harmony_add_link_to_card\`, \`harmony_remove_link_from_card\`, \`harmony_get_card_links\`

**Board:** \`harmony_get_board\`, \`harmony_list_projects\`, \`harmony_get_context\`, \`harmony_set_project_context\`

**Sessions:** \`harmony_start_agent_session\`, \`harmony_update_agent_progress\`, \`harmony_end_agent_session\`, \`harmony_get_agent_session\`

**AI:** \`harmony_generate_prompt\`, \`harmony_process_command\`
`;
/**
 * New Claude Code skill content with intent detection.
 */
const HMY_SKILL_CONTENT = `# Harmony Card Workflow

User input: $ARGUMENTS

## 0. Detect Intent

Parse \`$ARGUMENTS\` to determine what the user wants:

| Pattern | Intent | Go to |
|---|---|---|
| \`create ...\` or \`new ...\` | **Create** a new card | Step A |
| \`#42\`, \`42\`, UUID, or card name (no action verb) | **Work on** an existing card | Step B |
| \`move #42 to Done\`, \`update #42 ...\`, \`assign #42 ...\` | **Quick action** on a card | Step C |
| \`show #42\`, \`view #42\`, \`status #42\` | **View** card details | Step D |

If ambiguous, ask the user what they'd like to do.

---

## Step A: Create Card

Create a card without starting work on it.

1. Parse the title and any details from the arguments (e.g., \`create Add dark mode toggle\` → title: "Add dark mode toggle")
2. Call \`harmony_create_card\` with:
   - \`title\`: extracted title
   - \`description\`: if the user provided details beyond the title
   - \`priority\`, \`columnId\`, \`assigneeId\`: only if explicitly specified
3. Show the created card: title, short ID, column, and a link if available.
4. **Stop here.** Do not start an agent session or begin implementation.

---

## Step B: Work on Existing Card

Start work on a Harmony card.

### B1. Find & Fetch Card

Parse the reference and fetch the card:
- \`#42\` or \`42\` → \`harmony_get_card_by_short_id\` with \`shortId: 42\`
- UUID → \`harmony_get_card\` with \`cardId\`
- Name/text → \`harmony_search_cards\` with \`query\`

### B2. Start Agent Session

Call \`harmony_start_agent_session\` with:
- \`cardId\`: Card UUID
- \`agentIdentifier\`: Your agent identifier
- \`agentName\`: Your agent name
- \`currentTask\`: A specific description of the first thing you'll do (e.g., "Exploring codebase to understand auth flow"), NOT a generic phrase like "Analyzing card requirements"
- \`moveToColumn\`: "In Progress"
- \`addLabels\`: ["agent"]

This single call moves the card, adds the label, auto-assigns, and starts the session.

### B3. Generate Work Prompt

Call \`harmony_generate_prompt\` with:
- \`cardId\` or \`shortId\` (+ \`projectId\` if using shortId)
- \`variant\`: Select based on task:
  - \`"execute"\` (default) → Clear tasks, bug fixes, well-defined work
  - \`"analysis"\` → Complex features, unclear requirements
  - \`"draft"\` → Medium complexity, want feedback first

The generated prompt provides role framing, focus areas, subtasks, linked cards, and suggested outputs.

### B4. Display Card Summary

Show the user: Card title, short ID, role, priority, labels, due date, description, and subtasks.

### B5. Implement Solution

Work on the card following the generated prompt's guidance.

**REQUIRED: Update progress at each milestone** by calling \`harmony_update_agent_progress\`. This is not optional — the card's live status badge depends on these updates.

| Milestone | \`progressPercent\` | Example \`currentTask\` |
|---|---|---|
| After exploring codebase & understanding requirements | 20 | "Reading auth middleware and identifying affected routes" |
| When starting implementation | 50 | "Refactoring token validation in auth.ts" |
| When moving to testing/verification | 80 | "Running build and verifying changes compile" |
| When done, before ending session | 100 | "All changes complete, ready for review" |

Always set \`currentTask\` to a specific description of what you're actually doing — never leave it as "Analyzing card requirements" or other generic text.

### B6. Complete Work

When finished:
1. \`harmony_end_agent_session\` with \`status: "completed"\`, \`progressPercent: 100\`, \`moveToColumn: "Review"\`
2. Summarize accomplishments

If pausing: \`harmony_end_agent_session\` with \`status: "paused"\`

---

## Step C: Quick Action

Fetch the card first (same as B1), then perform the requested action:
- **Move:** \`harmony_move_card\` with target column
- **Update:** \`harmony_update_card\` with changed fields
- **Assign:** \`harmony_assign_card\`
- **Label:** \`harmony_add_label_to_card\` / \`harmony_remove_label_from_card\`
- **Archive:** \`harmony_archive_card\`

Show confirmation and stop. Do not start an agent session.

---

## Step D: View Card

Fetch the card (same as B1) and display: title, short ID, column, priority, labels, assignee, due date, description, subtasks, and links.

Do not start an agent session.

---

## Key Tools Reference

**Cards:** \`harmony_get_card\`, \`harmony_get_card_by_short_id\`, \`harmony_search_cards\`, \`harmony_create_card\`, \`harmony_update_card\`, \`harmony_move_card\`, \`harmony_delete_card\`, \`harmony_assign_card\`

**Subtasks:** \`harmony_create_subtask\`, \`harmony_toggle_subtask\`, \`harmony_delete_subtask\`

**Labels:** \`harmony_add_label_to_card\`, \`harmony_remove_label_from_card\`, \`harmony_create_label\`

**Links:** \`harmony_add_link_to_card\`, \`harmony_remove_link_from_card\`, \`harmony_get_card_links\`

**Board:** \`harmony_get_board\`, \`harmony_list_projects\`, \`harmony_get_context\`, \`harmony_set_project_context\`

**Sessions:** \`harmony_start_agent_session\`, \`harmony_update_agent_progress\`, \`harmony_end_agent_session\`, \`harmony_get_agent_session\`

**AI:** \`harmony_generate_prompt\`, \`harmony_process_command\`
`;
const HMY_PLAN_CONTENT = `# Harmony Plan Workflow

Create a new plan or work on an existing one. Argument: $ARGUMENTS

## Step 1 — Detect Intent

Parse \`$ARGUMENTS\` to determine the workflow:

- **UUID** (contains dashes, 36 chars) → call \`harmony_get_plan\` with \`planId\` directly → **Step 2A**
- **\`#N\`** (short ID) → call \`harmony_get_card_by_short_id\` to get the card, then \`harmony_get_plan\` with \`cardId\` → **Step 2A**
- **Text** (anything else) → call \`harmony_list_plans\` with \`search\` set to the text
  - If **one match** → use it → **Step 2A**
  - If **multiple matches** → list them with title, status, phase, and updated date. Ask the user to pick one using \`AskUserQuestion\` → **Step 2A**
  - If **no matches** → ask user: "No existing plans found for '$ARGUMENTS'. Would you like to create a new plan on this topic?" → **Step 2B**
- **Empty / vague topic** → **Step 2B** (create new plan)

---

## Step 2A — Work on Existing Plan

### 2A.1 — Analyze & Display

Once you have the plan ID, call \`harmony_get_plan\` to fetch the full plan with tasks. Show a structured summary:

\\\`\\\`\\\`
## [Plan Title]
**Status:** draft/active/archived | **Phase:** plan/execute/verify/done
**Tasks:** N total (X pending, Y in_progress, Z completed)
**URL:** https://app.gethmy.com/plans/{id}
\\\`\\\`\\\`

If plan is in execute phase and tasks already have linked cards, note which tasks have cards and which don't.

### 2A.2 — Recall Context

Call \`harmony_memory_search\` with the plan title to find related knowledge, patterns, or decisions that may inform execution.

### 2A.3 — Present Options

Use \`AskUserQuestion\` to offer execution choices. Adapt options based on plan state:

#### Default options (plan in \`plan\` phase):

**(A) Single card** — Create one card with plan summary + link to plan. Best for simple plans.
**(B) Multiple cards** — Create one card per task via \`harmony_advance_plan\`. Best for complex plans with independent tasks.
**(C) Analyze only** — Review the plan and design an implementation approach. Create cards later.
**(D) Skip** — Do nothing.

#### If plan has no tasks:
Only offer **(A) Single card**, **(C) Analyze only**, or **(D) Skip**.

#### If plan is already in \`execute\` phase with existing cards:
**(A) Work on existing cards** — List cards with short IDs, suggest \`/hmy #N\` to start
**(B) Create cards for remaining tasks** — Only create cards for tasks without linked cards
**(C) Analyze progress** — Review what's done vs remaining
**(D) Skip**

### 2A.4 — Execute Choice

#### Option A — Single card
1. Call \`harmony_create_card\` with:
   - \`title\`: Plan title
   - \`description\`: Brief 2-3 sentence summary of the plan + \`\\n\\n[View plan](https://app.gethmy.com/plans/{planId})\`
   - \`priority\`: based on plan task priorities (use highest)
2. Call \`harmony_update_plan\` to set \`status: "active"\`, \`workflowPhase: "execute"\`

#### Option B — Multiple cards (advance plan)
1. Call \`harmony_advance_plan\` with:
   - \`planId\`: the plan ID
   - \`phase\`: \`"execute"\`
   - \`summary\`: Brief summary of the plan scope
2. Display the created cards with their short IDs

#### Option C — Analyze only
1. Present a structured implementation analysis:
   - Suggested order of tasks
   - Dependencies between tasks
   - Key technical considerations from memory search
   - Estimated complexity
2. Suggest creating cards when ready

#### Option D — Skip
Acknowledge and stop.

### 2A.5 — Summary

After execution, show:
- Created card(s) with short IDs
- Current plan phase
- Suggest next step: \`/hmy #N\` to start working on a card

---

## Step 2B — Create New Plan

### 2B.1 — Context Gathering

Before interviewing, gather existing context:

1. Call \`harmony_get_board\` for board state (columns, cards, labels)
2. Call \`harmony_recall\` with relevant tags to find existing knowledge on the topic
3. Call \`harmony_memory_search\` with the topic to find related patterns/decisions/lessons

Note what you learn — reference it during the interview to ask smarter questions.

### 2B.2 — Structured Interview (3-5 questions)

Interview the user with **3-5 focused questions** using AskUserQuestion. Adapt based on complexity.

#### Core Questions
1. **Problem & Audience**: What problem are we solving? Who benefits?
2. **Scope**: What's in v1, what's deferred?
3. **Technical Constraints**: Any technical preferences, constraints, or existing patterns to follow?

#### Adaptive Follow-ups (if needed)
- Key user flows or interactions?
- Integration points with existing systems?
- Performance, security, or accessibility requirements?

#### Interview Rules
- Reference what you found in Step 2B.1 (board state, memories) to ask informed questions
- Skip questions that aren't relevant — simple features need fewer questions
- Tell the user when you have enough information to draft

### 2B.3 — Plan Document

Create a structured markdown document:

\\\`\\\`\\\`markdown
# [Title]

## Problem
[What problem we're solving and why]

## Scope

### In Scope
- [Feature/capability 1]
- [Feature/capability 2]

### Out of Scope
- [Deferred items]

## Approach
[Technical design, architecture decisions, key patterns]

### Key Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| ... | ... | ... |

## Tasks
1. **[Task title]** — priority: high
   [Brief description]

2. **[Task title]** — priority: medium
   [Brief description]

[Continue for all tasks...]

## Risks & Mitigations
| Risk | Mitigation |
|------|------------|
| ... | ... |

## Success Criteria
- [ ] [Measurable criterion]
\\\`\\\`\\\`

### 2B.4 — Create Plan

Call \`harmony_create_plan\` with:
- \`title\`: The plan title
- \`content\`: Full markdown document from Step 2B.3
- \`source\`: \`"agent"\`
- \`workflowPhase\`: \`"plan"\`
- \`tasks\`: Array of tasks from the Tasks section, each with:
  - \`content\`: Task title + brief description
  - \`priority\`: \`"high"\`, \`"medium"\`, or \`"low"\`
  - \`status\`: \`"pending"\`

### 2B.5 — User Approval

Show the user:
- Plan URL: \`https://app.gethmy.com/plans/{id}\`
- Number of tasks created
- Brief summary

Then ask: **"Ready to execute? I'll create board cards from these tasks and start the execution phase."**

Options:
1. **Yes, advance to Execute** — proceed to Step 2B.6
2. **Let me review first** — end here, they can advance later from the UI
3. **Make changes** — iterate on the plan

### 2B.6 — Advance to Execute

Call \`harmony_advance_plan\` with:
- \`planId\`: The plan ID from Step 2B.4
- \`phase\`: \`"execute"\`
- \`summary\`: A 2-3 sentence summary of the key decisions made during planning

Report the result:
- "Created N cards in 'To Do'. Use \`/hmy #<id>\` to start working on any card."
- List the created cards with their short IDs

## Key Tools Reference

**Discovery:** \`harmony_list_plans\`, \`harmony_get_plan\`, \`harmony_get_card_by_short_id\`
**Context:** \`harmony_get_board\`, \`harmony_recall\`, \`harmony_memory_search\`
**Planning:** \`harmony_create_plan\`, \`harmony_advance_plan\`, \`harmony_update_plan\`
**Execution:** \`harmony_create_card\`, \`harmony_update_card\`
`;
export const SKILL_DEFINITIONS = {
    hmy: {
        name: "hmy",
        description: "Work with Harmony cards — create, view, update, or start working on them. Use when given a card reference like #42, or commands like create, move, update.",
        argumentHint: "<command or card-reference>",
        content: HMY_SKILL_CONTENT,
    },
    "hmy-plan": {
        name: "hmy-plan",
        description: "Create a new plan or work on an existing one. Use when asked to plan a feature, execute a plan, review a plan, or given a plan reference.",
        argumentHint: "[plan name, ID, or topic to plan]",
        content: HMY_PLAN_CONTENT,
    },
};
/**
 * Build a complete skill file with frontmatter and version marker.
 * Optionally substitutes agent identifier/name for agent-specific builds.
 */
export function buildSkillFile(skillId, agentId) {
    const skill = SKILL_DEFINITIONS[skillId];
    if (!skill) {
        throw new Error(`Unknown skill: ${skillId}`);
    }
    let content = skill.content;
    // Apply agent-specific substitutions
    if (agentId === "claude") {
        content = content
            .replace("Your agent identifier", "claude-code")
            .replace("Your agent name", "Claude Code");
    }
    const frontmatter = `---
name: ${skill.name}
description: ${skill.description}
argument-hint: ${skill.argumentHint}
---`;
    return `${frontmatter}\n\n${content}\n${VERSION_MARKER_PREFIX}${SKILLS_VERSION} -->`;
}
/**
 * Parse the skills version from a skill file's content.
 * Returns null if no version marker is found.
 */
function parseSkillVersion(content) {
    const match = content.match(/<!-- skills-version:(\d+) -->/);
    return match ? match[1] : null;
}
/**
 * Find all skill files in a given directory (global or local).
 * Returns an array of { skillId, filePath } for each found skill.
 */
function findSkillFiles(paths) {
    const results = [];
    for (const filePath of paths) {
        if (!existsSync(filePath))
            continue;
        // Determine skill ID from path
        for (const skillId of Object.keys(SKILL_DEFINITIONS)) {
            if (filePath.includes(`/${skillId}/`) ||
                filePath.includes(`/${skillId}.md`)) {
                results.push({ skillId, filePath });
                break;
            }
        }
    }
    return results;
}
/**
 * Silently refresh installed skill files if they are outdated.
 * Called at MCP server startup. Non-blocking — errors are caught and logged.
 */
export async function refreshSkills() {
    try {
        const status = areSkillsInstalled();
        if (!status.installed) {
            // User hasn't run setup yet — don't install skills
            return;
        }
        // Find skill files from the detected paths
        const skillFiles = findSkillFiles(status.paths);
        // Also check for sibling skills in the same directory
        // e.g., if hmy is installed at ~/.agents/skills/hmy/SKILL.md,
        // check for hmy-plan at ~/.agents/skills/hmy-plan/SKILL.md
        if (skillFiles.length > 0) {
            const samplePath = skillFiles[0].filePath;
            for (const skillId of Object.keys(SKILL_DEFINITIONS)) {
                const alreadyFound = skillFiles.some((sf) => sf.skillId === skillId);
                if (alreadyFound)
                    continue;
                // Try to find sibling skill file
                let siblingPath;
                if (samplePath.endsWith("SKILL.md")) {
                    // ~/.agents/skills/hmy/SKILL.md -> ~/.agents/skills/hmy-plan/SKILL.md
                    const parentDir = dirname(dirname(samplePath));
                    siblingPath = `${parentDir}/${skillId}/SKILL.md`;
                }
                else {
                    // ~/.claude/skills/hmy.md -> ~/.claude/skills/hmy-plan.md
                    const parentDir = dirname(samplePath);
                    siblingPath = `${parentDir}/${skillId}.md`;
                }
                if (existsSync(siblingPath)) {
                    skillFiles.push({ skillId, filePath: siblingPath });
                }
            }
        }
        if (skillFiles.length === 0) {
            return;
        }
        let updated = false;
        for (const { skillId, filePath } of skillFiles) {
            try {
                const currentContent = readFileSync(filePath, "utf-8");
                const currentVersion = parseSkillVersion(currentContent);
                // Update if no version marker or version is older
                if (currentVersion === null ||
                    Number(currentVersion) < Number(SKILLS_VERSION)) {
                    const newContent = buildSkillFile(skillId, "claude");
                    const dir = dirname(filePath);
                    if (!existsSync(dir)) {
                        mkdirSync(dir, { recursive: true });
                    }
                    writeFileSync(filePath, newContent);
                    updated = true;
                }
            }
            catch {
                // Silently skip files we can't read/write
            }
        }
        if (updated) {
            console.error(`Harmony: Updated skills to v${SKILLS_VERSION}`);
        }
    }
    catch {
        // Non-blocking — if anything fails, continue silently
    }
}
