import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
import { registerSafetyHooks } from "./safety";
import { registerObservabilityHooks } from "./observability";
import { registerTools } from "./tools";

/**
 * ECC (Everything Claude Code) — oh-my-pi Extension
 *
 * Integrates ECC's safety hooks, session observability, custom tools,
 * and slash commands into the omp runtime.
 *
 * Auto-discovered via `package.json` → `omp.extensions` manifest.
 */
export default function eccExtension(pi: ExtensionAPI): void {
  const { z } = pi.zod;

  pi.setLabel("ECC - Everything Claude Code");

  // ── Phase 1: Safety hooks ──────────────────────────────────────────
  registerSafetyHooks(pi);

  // ── Phase 2: Observability ─────────────────────────────────────────
  registerObservabilityHooks(pi);

  // ── Phase 3: Custom tools ──────────────────────────────────────────
  registerTools(pi);

  // ── Phase 4: Slash commands ────────────────────────────────────────

  // /code-review — review uncommitted changes or a PR
  pi.registerCommand("code-review", {
    description:
      "Code review — local uncommitted changes or GitHub PR (pass PR number/URL for PR mode)",
    handler: async (args, ctx) => {
      const target = args.join(" ").trim();
      const msg = target
        ? `## Code Review\n\n**Target**: ${target}\n\nRunning code review. This command delegates to the ECC code-review skill.\n\nSee: skill://requesting-code-review`
        : "## Code Review (Local)\n\nReviewing uncommitted changes. Run `git diff HEAD` to see changes, then inspect each file for:\n- Hardcoded secrets\n- SQL injection\n- XSS\n- Missing input validation\n- Missing error handling\n- TODO/FIXME comments\n\nSee: skill://requesting-code-review";
      ctx.ui.notify("Code review initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /plan — implementation planning
  pi.registerCommand("plan", {
    description:
      "Restate requirements, assess risks, and create step-by-step implementation plan. WAIT for confirmation before coding",
    handler: async (args, ctx) => {
      const input = args.join(" ").trim() || "Clarify what should be planned.";
      const msg = `## Implementation Plan\n\n**Request**: ${input}\n\nAnalyzing requirements and creating plan. This command delegates to the ECC plan skill.\n\nSee: skill://writing-plans`;
      ctx.ui.notify("Planning initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /tdd — test-driven development workflow
  pi.registerCommand("tdd", {
    description:
      "Start test-driven development workflow: RED (write failing test) → GREEN (implement) → REFACTOR",
    handler: async (args, ctx) => {
      const feature = args.join(" ").trim() || "unnamed feature";
      const msg = `## TDD Workflow: ${feature}\n\nStarting test-driven development cycle:\n1. **RED** — Write a failing test first\n2. **GREEN** — Implement minimally to pass\n3. **REFACTOR** — Clean up while keeping tests green\n4. Verify 80%+ coverage\n\nSee: skill://test-driven-development`;
      ctx.ui.notify(`TDD cycle started for: ${feature}`, "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /security-scan — security audit
  pi.registerCommand("security-scan", {
    description:
      "Run security scan against agent configuration — secrets, permissions, MCP server safety",
    handler: async (args, ctx) => {
      const scanPath = args.join(" ").trim() || ".";
      const msg = `## Security Scan\n\n**Path**: ${scanPath}\n\nRunning security audit. This command delegates to the ECC security-scan skill.\n\nTry: \`npx ecc-agentshield scan --path "${scanPath}" --format text\`\n\nSee: skill://security-review`;
      ctx.ui.notify("Security scan initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /e2e — end-to-end test runner
  pi.registerCommand("e2e", {
    description:
      "E2E testing workflow — generate, run, and maintain Playwright/Agent Browser tests",
    handler: async (args, ctx) => {
      const target = args.join(" ").trim() || "all tests";
      const msg = `## E2E Testing\n\n**Target**: ${target}\n\nRunning E2E tests. This command delegates to the ECC e2e-testing skill.\n\nSee: skill://e2e-testing`;
      ctx.ui.notify("E2E testing initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /build-fix — incremental build error resolution
  pi.registerCommand("build-fix", {
    description:
      "Detect project build system and incrementally fix build/type errors with minimal safe changes",
    handler: async (args, ctx) => {
      const projectPath = args.join(" ").trim() || ".";
      const msg = `## Build Fix\n\n**Path**: ${projectPath}\n\nDetecting build system and fixing errors one at a time.\n\nSee: skill://tdd-workflow (build recovery patterns)`;
      ctx.ui.notify("Build fix initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /refactor-clean — dead code cleanup
  pi.registerCommand("refactor-clean", {
    description:
      "Safely identify and remove dead code with verification after each change",
    handler: async (args, ctx) => {
      const target = args.join(" ").trim() || ".";
      const msg = `## Dead Code Cleanup\n\n**Target**: ${target}\n\nIdentifying and removing dead code. This command delegates to the ECC refactor-clean command.\n\nSee: skill://improve-codebase-architecture`;
      ctx.ui.notify("Dead code cleanup initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /pr — create a GitHub pull request
  pi.registerCommand("pr", {
    description:
      "Create a GitHub PR from current branch with unpushed commits — discovers templates, analyzes changes, pushes",
    handler: async (args, ctx) => {
      const baseBranch = args[0] ?? "main";
      const msg = `## Create Pull Request\n\n**Base branch**: ${baseBranch}\n\nCreating PR from current branch. This command delegates to the ECC PR workflow.\n\nSee: skill://writing-plans (PR creation section)`;
      ctx.ui.notify(`Creating PR against ${baseBranch}`, "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });

  // /learn — extract reusable patterns from session
  pi.registerCommand("learn", {
    description:
      "Extract reusable patterns from the current session and save them as candidate skills or guidance",
    handler: async (args, ctx) => {
      const topic = args.join(" ").trim() || "session patterns";
      const msg = `## Learning: ${topic}\n\nAnalyzing session for reusable patterns. This command delegates to the ECC learn command.\n\nSee: skill://agent-introspection-debugging`;
      ctx.ui.notify("Learning session analysis initiated", "info");
      await pi.sendMessage(msg, { deliverAs: "followUp" });
    },
  });
}
