import {
  INIT_PATTERNS,
  INIT_STATUSES,
  PHASE_STATUSES,
  PRIORITIES
} from "./chunk-NAP6CFSO.js";
import {
  INIT_PATHS
} from "./chunk-ZHCZHZH3.js";
import {
  parseYAML,
  readWU,
  stringifyYAML
} from "./chunk-NRIZR3A7.js";
import {
  WU_PATHS
} from "./chunk-6HO4GWJE.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../initiatives/dist/initiative-yaml.js
import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
import path from "path";

// ../initiatives/dist/initiative-schema.js
import { z } from "zod";
var DATE_PATTERN = INIT_PATTERNS.DATE;
var InitiativePhaseSchema = z.object({
  /** Phase number (non-negative integer, determines sequence; 0 valid for foundation phases) */
  id: z.number().int().nonnegative({ message: "Phase id must be a non-negative integer" }),
  /** Phase title */
  title: z.string().min(1, { message: "Phase title is required" }),
  /** Phase status */
  status: z.enum(PHASE_STATUSES, {
    error: `Status must be one of: ${PHASE_STATUSES.join(", ")}`
  })
});
var InitiativeSchema = z.object({
  /** Initiative identifier (INIT-NNN or INIT-NAME format) */
  id: z.string().regex(INIT_PATTERNS.INIT_ID, { message: "ID must match pattern INIT-NNN or INIT-NAME" }),
  /** Kebab-case unique identifier for URLs and references */
  slug: z.string().regex(INIT_PATTERNS.SLUG, { message: "Slug must be kebab-case (e.g., shock-protocol)" }),
  /** Initiative title */
  title: z.string().min(1, { message: "Title is required" }),
  /** Detailed description (optional) */
  description: z.string().optional(),
  /** Initiative lifecycle status */
  status: z.enum(INIT_STATUSES, {
    error: `Status must be one of: ${INIT_STATUSES.join(", ")}`
  }),
  /** Priority level (optional) */
  priority: z.enum(PRIORITIES, {
    error: `Priority must be one of: ${PRIORITIES.join(", ")}`
  }).optional(),
  /** Owner (team or individual, optional) */
  owner: z.string().optional(),
  /** Creation date (YYYY-MM-DD) */
  created: z.string().regex(DATE_PATTERN, { message: "Created must be YYYY-MM-DD format" }),
  /** Target completion date (optional, YYYY-MM-DD) */
  target_date: z.string().regex(DATE_PATTERN, { message: "Target date must be YYYY-MM-DD format" }).optional(),
  /** Ordered phases within the initiative (optional) */
  phases: z.array(InitiativePhaseSchema).optional(),
  /** Success metrics for completion (optional) */
  success_metrics: z.array(z.string()).optional(),
  /** Labels for cross-cutting concerns (optional) */
  labels: z.array(z.string()).optional(),
  /** Linked WU IDs (optional, bidirectional link with WU.initiative field) */
  wus: z.array(z.string()).optional()
});
function validateInitiative(data) {
  return InitiativeSchema.safeParse(data);
}

// ../initiatives/dist/initiative-yaml.js
function readInitiative(initPath, expectedId) {
  if (!existsSync(initPath)) {
    throw createError(ErrorCodes.INIT_NOT_FOUND, `Initiative file not found: ${initPath}`, {
      path: initPath,
      expectedId
    });
  }
  const text = readFileSync(initPath, { encoding: "utf-8" });
  let rawDoc;
  try {
    rawDoc = parseYAML(text);
  } catch (e) {
    const errorMessage = e instanceof Error ? e.message : String(e);
    throw createError(ErrorCodes.YAML_PARSE_ERROR, `Failed to parse YAML ${initPath}: ${errorMessage}`, {
      path: initPath,
      originalError: errorMessage
    });
  }
  const docWithId = rawDoc;
  if (!docWithId || docWithId.id !== expectedId) {
    throw createError(ErrorCodes.INIT_NOT_FOUND, `Initiative YAML id mismatch. Expected ${expectedId}, found ${docWithId?.id}`, { path: initPath, expectedId, foundId: docWithId?.id });
  }
  const result = validateInitiative(rawDoc);
  if (!result.success) {
    const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Initiative validation failed: ${issues}`, {
      path: initPath,
      issues: result.error.issues
    });
  }
  return result.data;
}
function writeInitiative(initPath, doc) {
  const out = stringifyYAML(doc);
  writeFileSync(initPath, out, { encoding: "utf-8" });
}
function listInitiatives() {
  const dir = INIT_PATHS.INITIATIVES_DIR();
  if (!existsSync(dir)) {
    return [];
  }
  const files = readdirSync(dir).filter((f) => f.endsWith(".yaml") && INIT_PATTERNS.INIT_ID.test(f.replace(".yaml", "")));
  return files.map((f) => {
    const filePath = path.join(dir, f);
    const id = f.replace(".yaml", "");
    try {
      const doc = readInitiative(filePath, id);
      return { id, doc, path: filePath };
    } catch {
      return null;
    }
  }).filter((entry) => entry !== null);
}
function findInitiative(ref) {
  const initiatives = listInitiatives();
  const byId = initiatives.find((i) => i.id === ref);
  if (byId)
    return byId;
  const bySlug = initiatives.find((i) => i.doc.slug === ref);
  return bySlug || null;
}
function getInitiativeWUs(initRef) {
  const wuDir = WU_PATHS.WU("").replace(/\/[^/]*$/, "");
  if (!existsSync(wuDir)) {
    return [];
  }
  const files = readdirSync(wuDir).filter((f) => f.endsWith(".yaml") && f.startsWith("WU-"));
  const initiative = findInitiative(initRef);
  const matchRefs = initiative ? [initiative.id, initiative.doc.slug].filter(Boolean) : [initRef];
  return files.map((f) => {
    const filePath = path.join(wuDir, f);
    const id = f.replace(".yaml", "");
    try {
      const doc = readWU(filePath, id);
      if (doc.initiative && matchRefs.includes(doc.initiative)) {
        return { id, doc, path: filePath };
      }
      return null;
    } catch {
      return null;
    }
  }).filter((entry) => entry !== null);
}
function getInitiativeProgress(initRef) {
  const wus = getInitiativeWUs(initRef);
  const counts = {
    total: wus.length,
    done: 0,
    inProgress: 0,
    blocked: 0,
    ready: 0,
    percentage: 0
  };
  for (const { doc } of wus) {
    switch (doc.status) {
      case "done":
        counts.done++;
        break;
      case "in_progress":
        counts.inProgress++;
        break;
      case "blocked":
        counts.blocked++;
        break;
      case "ready":
        counts.ready++;
        break;
      default:
        break;
    }
  }
  counts.percentage = counts.total > 0 ? Math.round(counts.done / counts.total * 100) : 0;
  return counts;
}
function getInitiativePhases(initRef) {
  const wus = getInitiativeWUs(initRef);
  const phases = /* @__PURE__ */ new Map();
  for (const { id, doc } of wus) {
    const phase = doc.phase ?? null;
    if (!phases.has(phase)) {
      phases.set(phase, []);
    }
    phases.get(phase).push({ id, doc });
  }
  return phases;
}

export {
  readInitiative,
  writeInitiative,
  listInitiatives,
  findInitiative,
  getInitiativeWUs,
  getInitiativeProgress,
  getInitiativePhases
};
