#!/usr/bin/env node
/**
 * qa-stlc — CLI for QA STLC Agents
 *
 * Usage:
 *   qa-stlc init                    # Bootstrap MCP config + skills for current project
 *   qa-stlc skills [--target]       # Install skills into a coding agent
 *   qa-stlc mcp-config [--vscode]   # Write MCP server config
 *   qa-stlc verify                  # Check Python agents + Playwright MCP are reachable
 *   qa-stlc help                    # Show full help
 */

"use strict";

const { program } = require("commander");
const path = require("path");
const pkg = require("../package.json");

// Sub-commands
const cmdInit       = require("../src/cli/cmd-init");
const cmdSkills     = require("../src/cli/cmd-skills");
const cmdMcpConfig  = require("../src/cli/cmd-mcp-config");
const cmdVerify     = require("../src/cli/cmd-verify");
const cmdScaffold   = require("../src/cli/cmd-scaffold");
const cmdCost = require("../src/cli/cmd-cost");
const cmdUpgradeFramework = require("../src/cli/cmd-upgrade-framework");
const { formatNextSteps, quickStartHelpText } = require("../src/cli/next-steps");

program
  .name("qa-stlc")
  .description(
    "QA STLC Agents — MCP servers + skills for AI-powered test case, Gherkin, and Playwright generation."
  )
  .version(pkg.version);

// ── init ─────────────────────────────────────────────────────────────────────
program
  .command("init")
  .description(
    "Bootstrap the current project: install Python MCP agents, copy skills, and write MCP config.\n" +
    "Equivalent to running: pip install qa-gentic-stlc-agents && qa-stlc skills && qa-stlc mcp-config"
  )
  .option("--vscode", "Also write .vscode/mcp.json for GitHub Copilot")
  .option("--python <path>", "Path to Python 3.10+ binary", "python3")
  .option("--integration <value>", "Integration to set up: ado, jira, or both (prompts if omitted)")
  .action(cmdInit);

// ── skills ────────────────────────────────────────────────────────────────────
program
  .command("skills")
  .description("Install agent skill files into the current project for your coding agent to read.")
  .option(
    "--target <target>",
    "Where to install: claude (default), vscode, cursor, windsurf, print",
    "claude"
  )
  .option("--integration <value>", "Integration to install: ado, jira, or both")
  .action(cmdSkills);

// ── mcp-config ────────────────────────────────────────────────────────────────
program
  .command("mcp-config")
  .description("Generate MCP server configuration for Claude Code (.mcp.json) or VS Code (.vscode/mcp.json).")
  .option("--vscode", "Write .vscode/mcp.json instead of .mcp.json")
  .option("--print", "Print config to stdout without writing any file")
  .option("--python <path>", "Path to Python 3.10+ binary or venv", "python3")
  .option("--playwright-port <port>", "Port Playwright MCP is running on", "8931")
  .option("--integration <value>", "Override integration filter: ado, jira, or both")
  .action(cmdMcpConfig);

// ── verify ────────────────────────────────────────────────────────────────────
program
  .command("verify")
  .description("Check that Python MCP agents are installed and Playwright MCP is reachable.")
  .option("--playwright-port <port>", "Port Playwright MCP is running on", "8931")
  .action(cmdVerify);

// ── scaffold ──────────────────────────────────────────────────────────────────
program
  .command("scaffold")
  .description(
    "Scaffold a new Playwright + Cucumber + TypeScript QA project from the Healix boilerplate.\n" +
    "Includes three-layer AI self-healing, BDD templates, and CI/CD integration."
  )
  .option("--name <name>", "Project name (used in package.json and directory)", "my-qa-project")
  .option("--dir  <dir>",  "Output directory (defaults to ./<name>)")
  .option("--no-install",  "Skip npm install after scaffolding")
  .action(cmdScaffold);

// ── upgrade-framework ─────────────────────────────────────────────────────────
program
  .command("upgrade-framework")
  .description(
    "Refresh the self-healing framework files (src/utils/locators/*, src/utils/storage-state/*)\n" +
    "in an existing scaffolded repo from the bundled boilerplate. Diff-aware and dry-run by default."
  )
  .option("--apply", "Write the bundle versions over drifted/missing files (originals backed up to .bak.<ts>)")
  .option("--dir <dir>", "Repo root to upgrade (defaults to current working directory)")
  .option("--include <regex...>", "Extra path-regex(es) to include beyond the default framework scope")
  .action(cmdUpgradeFramework);

  program
  .command("cost")
  .description(
    "Show token usage and cost for stlc-agents pipeline sessions.\n" +
    "Reads logs from ~/.qa-stlc/cost-*.jsonl written on every MCP tool call.\n\n" +
    "Model detection order (first match wins):\n" +
    "  1. STLC_CODING_AGENT_MODEL env var     (explicit override)\n" +
    "  2. ANTHROPIC_MODEL env var             (set automatically by Claude Code)\n" +
    "  3. GITHUB_COPILOT_MODEL env var        (set by Copilot if configured)\n" +
    "  4. ~/.qa-stlc/agent-model file         (saved by --set-model)\n" +
    "  5. claude-sonnet-4-6                   (default fallback)\n\n" +
    "Claude Code users: no setup needed — model is detected automatically.\n" +
    "Cursor / Windsurf users: run  qa-stlc cost --set-model <model-id>  once."
  )
  .option("--all",              "Show all sessions (default: last session only)")
  .option("--session <id>",     "Show a specific session by ID")
  .option("--json",             "Output raw JSON instead of a formatted table")
  .option("--set-model <model>","Save your coding agent model for accurate pricing.\n" +
    "                             e.g. claude-opus-4-6 | gpt-4o | claude-sonnet-4-6")
  .option("--model-help",       "Explain model detection and all ways to configure it")
  .action(cmdCost);
  
// ── Quick-start hint appended to every --help output ─────────────────────────
program.addHelpText("after", quickStartHelpText());

// Show next-step instructions if invoked with no command.
// This is the reliable fallback when npm suppresses postinstall output.
if (!process.argv.slice(2).length) {
  console.log(formatNextSteps({ version: pkg.version }));
  process.exit(0);
}

program.parse(process.argv);