"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var index_exports = {};
__export(index_exports, {
  analyzeUnified: () => analyzeUnified,
  generateUnifiedSummary: () => generateUnifiedSummary,
  scoreUnified: () => scoreUnified
});
module.exports = __toCommonJS(index_exports);
var import_core = require("@aiready/core");
var import_pattern_detect = require("@aiready/pattern-detect");
var import_context_analyzer = require("@aiready/context-analyzer");
var import_consistency = require("@aiready/consistency");
var import_ai_signal_clarity = require("@aiready/ai-signal-clarity");
var import_agent_grounding = require("@aiready/agent-grounding");
var import_testability = require("@aiready/testability");
var import_doc_drift = require("@aiready/doc-drift");
var import_deps = require("@aiready/deps");
var import_change_amplification = require("@aiready/change-amplification");
var TOOL_PACKAGE_MAP = {
  [import_core.ToolName.PatternDetect]: "@aiready/pattern-detect",
  [import_core.ToolName.ContextAnalyzer]: "@aiready/context-analyzer",
  [import_core.ToolName.NamingConsistency]: "@aiready/consistency",
  [import_core.ToolName.AiSignalClarity]: "@aiready/ai-signal-clarity",
  [import_core.ToolName.AgentGrounding]: "@aiready/agent-grounding",
  [import_core.ToolName.TestabilityIndex]: "@aiready/testability",
  [import_core.ToolName.DocDrift]: "@aiready/doc-drift",
  [import_core.ToolName.DependencyHealth]: "@aiready/deps",
  [import_core.ToolName.ChangeAmplification]: "@aiready/change-amplification",
  // Aliases handled by registry
  patterns: "@aiready/pattern-detect",
  duplicates: "@aiready/pattern-detect",
  context: "@aiready/context-analyzer",
  fragmentation: "@aiready/context-analyzer",
  consistency: "@aiready/consistency",
  "naming-consistency": "@aiready/consistency",
  "ai-signal": "@aiready/ai-signal-clarity",
  "ai-signal-clarity": "@aiready/ai-signal-clarity",
  grounding: "@aiready/agent-grounding",
  "agent-grounding": "@aiready/agent-grounding",
  testability: "@aiready/testability",
  "testability-index": "@aiready/testability",
  "doc-drift": "@aiready/doc-drift",
  "deps-health": "@aiready/deps",
  "dependency-health": "@aiready/deps",
  "change-amp": "@aiready/change-amplification",
  "change-amplification": "@aiready/change-amplification"
};
async function analyzeUnified(options) {
  const startTime = Date.now();
  const requestedTools = options.tools || [
    "patterns",
    "context",
    "consistency"
  ];
  const result = {
    summary: {
      totalIssues: 0,
      totalFiles: 0,
      toolsRun: [],
      executionTime: 0
    }
  };
  for (const toolName of requestedTools) {
    let provider = import_core.ToolRegistry.find(toolName);
    if (!provider) {
      const packageName = TOOL_PACKAGE_MAP[toolName] || (toolName.startsWith("@aiready/") ? toolName : `@aiready/${toolName}`);
      try {
        await import(packageName);
        provider = import_core.ToolRegistry.find(toolName);
        if (provider) {
          console.log(
            `\u2705 Successfully loaded tool provider: ${toolName} from ${packageName}`
          );
        } else {
          console.log(
            `\u26A0\uFE0F Loaded ${packageName} but provider ${toolName} still not found in registry.`
          );
        }
      } catch (err) {
        console.log(
          `\u274C Failed to dynamically load tool ${toolName} (${packageName}):`,
          err.message
        );
      }
    }
    if (!provider) {
      console.warn(
        `\u26A0\uFE0F  Warning: Tool provider for '${toolName}' not found. Skipping.`
      );
      continue;
    }
    try {
      const output = await provider.analyze({
        ...options,
        onProgress: (processed, total, message) => {
          if (options.progressCallback) {
            options.progressCallback({
              tool: provider.id,
              processed,
              total,
              message
            });
          }
        }
      });
      if (options.progressCallback) {
        options.progressCallback({ tool: provider.id, data: output });
      }
      result[provider.id] = output;
      result.summary.toolsRun.push(provider.id);
      const toolFiles = output.summary?.totalFiles || output.summary?.filesAnalyzed || 0;
      if (toolFiles > result.summary.totalFiles) {
        result.summary.totalFiles = toolFiles;
      }
      const issueCount = output.results.reduce(
        (sum, file) => sum + (file.issues?.length || 0),
        0
      );
      result.summary.totalIssues += issueCount;
      if (provider.alias && Array.isArray(provider.alias)) {
        for (const alias of provider.alias) {
          if (!result[alias]) {
            result[alias] = output;
          }
        }
      }
      const camelCaseId = provider.id.replace(
        /-([a-z])/g,
        (g) => g[1].toUpperCase()
      );
      if (camelCaseId !== provider.id && !result[camelCaseId]) {
        result[camelCaseId] = output;
      }
    } catch (err) {
      console.error(`\u274C Error running tool '${provider.id}':`, err);
    }
  }
  result.summary.executionTime = Date.now() - startTime;
  return result;
}
async function scoreUnified(results, options) {
  const toolScores = /* @__PURE__ */ new Map();
  for (const toolId of results.summary.toolsRun) {
    const provider = import_core.ToolRegistry.get(toolId);
    if (!provider) continue;
    const output = results[toolId];
    if (!output) continue;
    try {
      const toolScore = provider.score(output, options);
      if (!toolScore.tokenBudget) {
        if (toolId === import_core.ToolName.PatternDetect && output.duplicates) {
          const wastedTokens = output.duplicates.reduce(
            (sum, d) => sum + (d.tokenCost || 0),
            0
          );
          toolScore.tokenBudget = (0, import_core.calculateTokenBudget)({
            totalContextTokens: wastedTokens * 2,
            wastedTokens: {
              duplication: wastedTokens,
              fragmentation: 0,
              chattiness: 0
            }
          });
        } else if (toolId === import_core.ToolName.ContextAnalyzer && output.summary) {
          toolScore.tokenBudget = (0, import_core.calculateTokenBudget)({
            totalContextTokens: output.summary.totalTokens,
            wastedTokens: {
              duplication: 0,
              fragmentation: output.summary.totalPotentialSavings || 0,
              chattiness: 0
            }
          });
        }
      }
      toolScores.set(toolId, toolScore);
    } catch (err) {
      console.error(`\u274C Error scoring tool '${toolId}':`, err);
    }
  }
  if (toolScores.size === 0) {
    return {
      overall: 0,
      rating: "Critical",
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      toolsUsed: [],
      breakdown: [],
      calculation: {
        formula: "0 / 0 = 0",
        weights: {},
        normalized: "0 / 0 = 0"
      }
    };
  }
  return (0, import_core.calculateOverallScore)(toolScores, options, void 0);
}
function generateUnifiedSummary(result) {
  const { summary } = result;
  let output = `\u{1F680} AIReady Analysis Complete

`;
  output += `\u{1F4CA} Summary:
`;
  output += `   Tools run: ${summary.toolsRun.join(", ")}
`;
  output += `   Total issues found: ${summary.totalIssues}
`;
  output += `   Execution time: ${(summary.executionTime / 1e3).toFixed(2)}s

`;
  for (const provider of import_core.ToolRegistry.getAll()) {
    const toolResult = result[provider.id];
    if (toolResult) {
      const issueCount = toolResult.results.reduce(
        (sum, r) => sum + (r.issues?.length || 0),
        0
      );
      output += `\u2022 ${provider.id}: ${issueCount} issues
`;
    }
  }
  return output;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  analyzeUnified,
  generateUnifiedSummary,
  scoreUnified
});
