import {
  resolveAllSkillsDirs
} from "./chunk-6B6UN6SG.js";
import {
  SkillMetadataSchema
} from "./chunk-HIK6OEUF.js";

// src/skill/index-builder.ts
import fs from "fs";
import path from "path";
import crypto from "crypto";
import { parse } from "yaml";
function computeSkillsDirHash(skillsDirs) {
  const hash = crypto.createHash("sha256");
  for (const dir of skillsDirs) {
    if (!fs.existsSync(dir)) continue;
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
      if (!entry.isDirectory()) continue;
      const yamlPath = path.join(dir, entry.name, "skill.yaml");
      if (!fs.existsSync(yamlPath)) continue;
      const stat = fs.statSync(yamlPath);
      hash.update(`${yamlPath}:${stat.mtimeMs}`);
    }
  }
  return hash.digest("hex");
}
function parseSkillEntry(yamlPath, source, tierOverrides) {
  const raw = fs.readFileSync(yamlPath, "utf-8");
  const parsed = parse(raw);
  const result = SkillMetadataSchema.safeParse(parsed);
  if (!result.success) return null;
  const meta = result.data;
  const effectiveTier = tierOverrides?.[meta.name] ?? meta.tier;
  if (meta.internal) return null;
  return {
    tier: effectiveTier ?? 3,
    type: meta.type,
    description: meta.description,
    keywords: meta.keywords ?? [],
    stackSignals: meta.stack_signals ?? [],
    cognitiveMode: meta.cognitive_mode,
    phases: (meta.phases ?? []).map((p) => p.name),
    paths: meta.paths ?? [],
    relatedSkills: meta.related_skills ?? [],
    source,
    addresses: meta.addresses ?? [],
    dependsOn: meta.depends_on ?? [],
    triggers: meta.triggers ?? ["manual"],
    ...meta.context_budget && {
      contextBudget: {
        maxTokens: meta.context_budget.max_tokens,
        priority: meta.context_budget.priority
      }
    }
  };
}
function scanDirectory(dir, source, index, tierOverrides) {
  if (!fs.existsSync(dir)) return;
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (!entry.isDirectory()) continue;
    if (index.skills[entry.name]) continue;
    const yamlPath = path.join(dir, entry.name, "skill.yaml");
    if (!fs.existsSync(yamlPath)) continue;
    try {
      const parsed = parseSkillEntry(yamlPath, source, tierOverrides);
      if (parsed) index.skills[entry.name] = parsed;
    } catch {
      continue;
    }
  }
}
function buildIndex(platform, _projectRoot, tierOverrides) {
  const skillsDirs = resolveAllSkillsDirs(platform);
  const sourceMap = ["project", "community", "bundled"];
  const index = {
    version: 1,
    hash: computeSkillsDirHash(skillsDirs),
    generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    skills: {}
  };
  for (let i = 0; i < skillsDirs.length; i++) {
    scanDirectory(skillsDirs[i], sourceMap[i] ?? "bundled", index, tierOverrides);
  }
  return index;
}
function loadOrRebuildIndex(platform, projectRoot, tierOverrides) {
  const indexPath = path.join(projectRoot, ".harness", "skills-index.json");
  const skillsDirs = resolveAllSkillsDirs(platform);
  const currentHash = computeSkillsDirHash(skillsDirs);
  if (fs.existsSync(indexPath)) {
    try {
      const existing = JSON.parse(fs.readFileSync(indexPath, "utf-8"));
      if (existing.hash === currentHash) return existing;
    } catch {
    }
  }
  const index = buildIndex(platform, projectRoot, tierOverrides);
  fs.mkdirSync(path.dirname(indexPath), { recursive: true });
  fs.writeFileSync(indexPath, JSON.stringify(index, null, 2));
  return index;
}

export {
  computeSkillsDirHash,
  buildIndex,
  loadOrRebuildIndex
};
