import "../../chunks/chunk.QU3DSPNU.js";
import { capitalize } from "../../utils/helpers/casing.js";
import { DOC_TYPES, PATHS, SEARCH_CONFIG, URI_SCHEME } from "./constants.js";
import { NotFoundError } from "./errors.js";
import { parseSearchQuery, performSearch } from "./search.js";
import {
  buildResourceUri,
  findComponent,
  findIcon,
  loadComponentsIndex,
  loadGlobalIndex,
  loadIconsIndex,
  parseResourceUri,
  readMcpFile
} from "./utils.js";
import {
  validateGetComponentDocsInput,
  validateGetGuideInput,
  validateListGuidesInput,
  validateSearchComponentsInput
} from "./validation.js";
async function handleSearchComponents(input) {
  const validatedInput = validateSearchComponentsInput(input);
  const {
    query,
    category = "all",
    splitTerms = true,
    matchAll = false,
    useRegex = false,
    maxResults = SEARCH_CONFIG.DEFAULT_MAX_RESULTS
  } = validatedInput;
  const loadComponents = category === "component" || category === "all";
  const loadIcons = category === "icon" || category === "all";
  const [componentsIndex, iconsIndex] = await Promise.all([
    loadComponents ? loadComponentsIndex() : Promise.resolve(null),
    loadIcons ? loadIconsIndex() : Promise.resolve(null)
  ]);
  const components = componentsIndex?.components || [];
  const icons = iconsIndex?.icons || [];
  const { searchTerms, regexPattern } = parseSearchQuery(
    query,
    splitTerms,
    useRegex
  );
  const buildUris = (item, cat) => {
    const shortName = item.tagName.replace(/^gds-/, "");
    const resourceCategory = cat === "component" ? "components" : "icons";
    const uris = {};
    for (const docType of item.files) {
      uris[docType] = buildResourceUri(resourceCategory, shortName, docType);
    }
    return uris;
  };
  const results = performSearch(
    components,
    icons,
    query,
    searchTerms,
    regexPattern,
    matchAll,
    splitTerms,
    maxResults,
    buildUris
  );
  return {
    content: [
      {
        type: "text",
        text: JSON.stringify(
          {
            query,
            resultCount: results.length,
            results
          },
          null,
          2
        )
      }
    ]
  };
}
async function handleGetComponentDocs(input) {
  const validatedInput = validateGetComponentDocsInput(input);
  const {
    componentName,
    framework,
    includeGuidelines = true,
    includeInstructions = true
  } = validatedInput;
  const [componentsIndex, iconsIndex] = await Promise.all([
    loadComponentsIndex(),
    loadIconsIndex()
  ]);
  if (!componentsIndex || !iconsIndex) {
    throw new NotFoundError(
      "Failed to load component indexes",
      "index",
      "components/icons"
    );
  }
  const component = findComponent(componentName, componentsIndex.components);
  const icon = component ? null : findIcon(componentName, iconsIndex.icons);
  const found = component || icon;
  if (!found) {
    throw new NotFoundError(
      `Component not found: ${componentName}. Try using the search_components tool to find available components.`,
      "component",
      componentName
    );
  }
  const shortName = found.tagName.replace(/^gds-/, "");
  const sections = [];
  let primaryDoc;
  if (framework === "angular") {
    primaryDoc = DOC_TYPES.ANGULAR;
  } else if (framework === "react") {
    primaryDoc = DOC_TYPES.REACT;
  } else {
    primaryDoc = DOC_TYPES.API;
  }
  sections.push(`# ${found.tagName} - ${capitalize(framework)}`);
  sections.push("");
  if (framework === "angular" || framework === "react") {
    sections.push(`\u26A0\uFE0F **${capitalize(framework)}-Specific Documentation**`);
    sections.push(
      `The import paths and syntax below are for ${capitalize(framework)} applications.`
    );
    sections.push("");
  }
  if (found.files.includes(primaryDoc)) {
    const content = await readMcpFile(`${shortName}/${primaryDoc}.md`);
    if (content) {
      const contentWithoutTitle = content.replace(/^#\s+.*?\n/, "");
      sections.push(contentWithoutTitle);
      sections.push("");
    }
  }
  if ((framework === "angular" || framework === "react") && found.files.includes(DOC_TYPES.API)) {
    const apiContent = await readMcpFile(`${shortName}/${DOC_TYPES.API}.md`);
    if (apiContent) {
      sections.push("---");
      sections.push("");
      sections.push("## Component API Reference");
      sections.push("");
      sections.push(
        "The following properties, events, slots, and methods are available:"
      );
      sections.push("");
      const apiWithoutHeader = apiContent.replace(/^#\s+.*?\n/, "").replace(/\*\*Class\*\*:.*?\n/, "").replace(/\*\*Tag\*\*:.*?\n/, "").trim();
      sections.push(apiWithoutHeader);
      sections.push("");
    }
  }
  if (includeGuidelines && found.files.includes(DOC_TYPES.GUIDELINES)) {
    const guidelines = await readMcpFile(
      `${shortName}/${DOC_TYPES.GUIDELINES}.md`
    );
    if (guidelines) {
      sections.push("---");
      sections.push("");
      sections.push("## Design Guidelines");
      sections.push("");
      sections.push(guidelines);
      sections.push("");
    }
  }
  if (includeInstructions && found.files.includes(DOC_TYPES.INSTRUCTIONS)) {
    const instructions = await readMcpFile(
      `${shortName}/${DOC_TYPES.INSTRUCTIONS}.md`
    );
    if (instructions) {
      sections.push("---");
      sections.push("");
      sections.push("## Usage Instructions");
      sections.push("");
      sections.push(instructions);
      sections.push("");
    }
  }
  sections.push("---");
  sections.push("");
  sections.push("\u{1F4A1} **Using a different framework?**");
  sections.push("Call this tool again with:");
  if (framework !== "angular")
    sections.push('- `framework: "angular"` for Angular documentation');
  if (framework !== "react")
    sections.push('- `framework: "react"` for React documentation');
  if (framework !== "web-component")
    sections.push('- `framework: "web-component"` for vanilla JS usage');
  return {
    content: [
      {
        type: "text",
        text: sections.join("\n")
      }
    ]
  };
}
async function handleListGuides(input) {
  const validatedInput = validateListGuidesInput(input);
  const { category = "all", framework } = validatedInput;
  const globalIndex = await loadGlobalIndex();
  if (!globalIndex) {
    throw new NotFoundError("Failed to load global index", "index", "global");
  }
  let guides = globalIndex.guides;
  if (category !== "all") {
    guides = guides.filter((g) => g.category === category);
  }
  if (framework && framework !== "all") {
    guides = guides.filter((g) => g.tags.includes(framework));
  }
  const guidesWithUris = guides.map((guide) => {
    const name = guide.path.replace(/^(guides|concepts)\//, "").replace(/\.md$/, "");
    const guideCategory = guide.path.startsWith("guides/") ? "guides" : "concepts";
    const uri = buildResourceUri(guideCategory, name);
    return {
      title: guide.title,
      category: guide.category,
      description: guide.description,
      tags: guide.tags,
      resourceUri: uri
    };
  });
  return {
    content: [
      {
        type: "text",
        text: JSON.stringify(
          {
            guideCount: guidesWithUris.length,
            guides: guidesWithUris
          },
          null,
          2
        )
      }
    ]
  };
}
async function handleGetGuide(input) {
  const validatedInput = validateGetGuideInput(input);
  const { name } = validatedInput;
  const globalIndex = await loadGlobalIndex();
  if (!globalIndex) {
    throw new NotFoundError("Failed to load global index", "index", "global");
  }
  const guide = globalIndex.guides.find((g) => {
    const guideName = g.path.replace(/^(guides|concepts)\//, "").replace(/\.md$/, "");
    return guideName === name;
  });
  if (!guide) {
    throw new NotFoundError(
      `Guide not found: ${name}. Use list_guides to see available guides.`,
      "guide",
      name
    );
  }
  const content = await readMcpFile(guide.path);
  if (!content) {
    throw new NotFoundError(
      `Guide file not found: ${guide.path}`,
      "file",
      guide.path
    );
  }
  return {
    content: [
      {
        type: "text",
        text: `# ${guide.title}

${content}`
      }
    ]
  };
}
async function handleGetInstructions() {
  const globalIndex = await loadGlobalIndex();
  if (!globalIndex) {
    throw new NotFoundError("Failed to load global index", "index", "global");
  }
  if (!globalIndex.instructions) {
    throw new NotFoundError(
      "Instructions not available. The MCP may not have been generated with instructions support.",
      "file",
      "INSTRUCTIONS.md"
    );
  }
  const content = await readMcpFile("INSTRUCTIONS.md");
  if (!content) {
    throw new NotFoundError(
      "Instructions file not found",
      "file",
      "INSTRUCTIONS.md"
    );
  }
  return {
    content: [
      {
        type: "text",
        text: content
      }
    ]
  };
}
async function handleResolveUri(uri) {
  if (uri === URI_SCHEME.INSTRUCTIONS) {
    const content2 = await readMcpFile(PATHS.INSTRUCTIONS_FILE);
    if (!content2) {
      throw new NotFoundError(
        "Instructions file not found",
        "file",
        PATHS.INSTRUCTIONS_FILE
      );
    }
    return {
      content: [{ type: "text", text: content2 }]
    };
  }
  const parsed = parseResourceUri(uri);
  if (!parsed) {
    throw new NotFoundError(`Invalid resource URI format: ${uri}`, "uri", uri);
  }
  const { category, name, docType } = parsed;
  let filePath;
  if (category === "components" || category === "icons") {
    if (!docType) {
      throw new NotFoundError(
        `Document type required for ${category} URIs (e.g. green://${category}/${name}/api)`,
        "docType",
        uri
      );
    }
    filePath = `${name}/${docType}.md`;
  } else if (category === "guides" || category === "concepts") {
    filePath = `${category}/${name}.md`;
  } else {
    throw new NotFoundError(`Unknown category: ${category}`, "category", uri);
  }
  const content = await readMcpFile(filePath);
  if (!content) {
    throw new NotFoundError(`Resource not found: ${uri}`, "file", filePath);
  }
  return {
    content: [{ type: "text", text: content }]
  };
}
export {
  handleGetComponentDocs,
  handleGetGuide,
  handleGetInstructions,
  handleListGuides,
  handleResolveUri,
  handleSearchComponents
};
