import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box, Text, useInput } from "ink";
import { semantic } from "../theme/palette.js";
import { CategoryScreen } from "./CategoryScreen.js";
import { save as runSave, installAgent } from "../state/propagation.js";
import {
  runSystemCheck
} from "../system-check.js";
import { defaultConfigPath } from "../../../persisted-config.js";
const ADVANCE_GUARD_MS = 50;
const STEP_LABEL = {
  1: "Welcome",
  2: "System",
  3: "LLM Provider",
  4: "MCP Agents",
  5: "Complete"
};
function StepHeader({ step }) {
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
    /* @__PURE__ */ jsx(Text, { dimColor: true, children: `Step ${step} / 4` }),
    /* @__PURE__ */ jsx(Text, { bold: true, children: STEP_LABEL[step] })
  ] });
}
function WelcomeStep(props) {
  useInput((_input, key) => {
    if (key.return) {
      props.onNext();
      return;
    }
    if (key.escape) {
      props.onSkip();
    }
  });
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(StepHeader, { step: 1 }),
    /* @__PURE__ */ jsx(Text, { children: "Welcome to wigolo \u2014 local-first web intelligence for AI agents." }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to begin \xB7 Esc to skip and use defaults" }) })
  ] });
}
function SystemStep(props) {
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  useEffect(() => {
    const impl = props.runSystemCheckImpl ?? runSystemCheck;
    let cancelled = false;
    void (async () => {
      try {
        const r = await impl();
        if (!cancelled) setResult(r);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : String(err));
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [props.runSystemCheckImpl]);
  useInput((_input, key) => {
    if (key.escape) {
      props.onSkip();
      return;
    }
    if (key.return && (result !== null || error !== null)) {
      props.onNext();
    }
  });
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(StepHeader, { step: 2 }),
    result === null && error === null ? /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Checking your system\u2026" }) : null,
    error !== null ? /* @__PURE__ */ jsx(Text, { color: semantic.warn, children: `System check error: ${error}` }) : null,
    result !== null ? /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
      /* @__PURE__ */ jsxs(Text, { children: [
        result.node.ok ? "\u2713" : "!",
        " Node ",
        result.node.version ?? "(unknown)"
      ] }),
      /* @__PURE__ */ jsxs(Text, { children: [
        result.python.ok ? "\u2713" : "!",
        " Python ",
        result.python.version ?? "(missing)"
      ] }),
      /* @__PURE__ */ jsxs(Text, { children: [
        result.docker.ok ? "\u2713" : "\xB7",
        " Docker",
        " ",
        result.docker.version ?? "(optional, not detected)"
      ] }),
      /* @__PURE__ */ jsxs(Text, { children: [
        result.disk.ok ? "\u2713" : "!",
        " Disk",
        " ",
        result.disk.freeMb !== void 0 ? `${result.disk.freeMb} MB free` : "(unknown)"
      ] }),
      result.hardFailure ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: semantic.warn, children: "One or more required tools are missing. You can continue and fix later." }) }) : null
    ] }) : null,
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to continue \xB7 Esc to skip remaining steps" }) })
  ] });
}
const CEREMONY_DELAY_MS = 1500;
function SetupComplete({ onDone }) {
  useEffect(() => {
    const t = setTimeout(onDone, CEREMONY_DELAY_MS);
    return () => clearTimeout(t);
  }, [onDone]);
  useInput((_input, key) => {
    if (key.return) {
      onDone();
    }
  });
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(Text, { color: semantic.ok, bold: true, children: "\u2713 Setup complete" }),
    /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2500".repeat(24) }),
    /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
      "Saved to ",
      defaultConfigPath()
    ] }),
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press \u23CE to continue (auto-dismiss in 1.5s)" }) })
  ] });
}
function findCategory(catalog, id) {
  return catalog.find((c) => c.id === id);
}
function WizardSteps(props) {
  const {
    store,
    catalog,
    configPath,
    agents,
    secretStore,
    onDone,
    onSkip,
    runSystemCheckImpl,
    saveImpl,
    installAgentImpl
  } = props;
  const [step, setStep] = useState(1);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);
  const [setupComplete, setSetupComplete] = useState(false);
  const llmCategory = useMemo(() => findCategory(catalog, "llm"), [catalog]);
  const agentsCategory = useMemo(() => findCategory(catalog, "agents"), [catalog]);
  const runFinish = useCallback(async () => {
    if (saving) return;
    setSaving(true);
    setSaveError(null);
    let hadError = false;
    try {
      const pending = store.getPending();
      const current = store.getCurrent();
      const selectedAgentsRaw = pending.agents !== void 0 ? pending.agents : current.agents;
      const selectedAgentIds = Array.isArray(selectedAgentsRaw) ? selectedAgentsRaw : [];
      const envBlock = {};
      for (const cat of catalog) {
        for (const field of cat.fields) {
          if (field.propagateToAgents === false) continue;
          const path = field.settingsPath;
          const raw = pending[path] !== void 0 ? pending[path] : current[path];
          if (raw === void 0 || raw === null) continue;
          if (typeof raw === "object") continue;
          envBlock[field.key] = String(raw);
        }
      }
      if (secretStore) {
        const save = saveImpl ?? runSave;
        const result = await save({
          store,
          catalog,
          configPath,
          agents: agents ?? [],
          secretStore
        });
        if (result.errors && result.errors.length > 0) {
          const msg = result.errors.map((e) => `${e.key}: ${e.reason}`).join("; ");
          setSaveError(msg);
          hadError = true;
        }
      } else {
        store.commit();
      }
      if (agents && agents.length > 0 && selectedAgentIds.length > 0) {
        const install = installAgentImpl ?? installAgent;
        for (const id of selectedAgentIds) {
          const target = agents.find((a) => a.id === id);
          if (!target) continue;
          try {
            await install({ target, env: envBlock });
          } catch (err) {
            const reason = err instanceof Error ? err.message : String(err);
            setSaveError(reason);
            hadError = true;
          }
        }
      }
    } finally {
      setSaving(false);
    }
    if (!hadError) {
      setSetupComplete(true);
    } else {
      onDone();
    }
  }, [
    saving,
    store,
    catalog,
    configPath,
    agents,
    secretStore,
    saveImpl,
    installAgentImpl,
    onDone
  ]);
  const advanceFromCategory = useCallback(() => {
    if (step === 3) {
      setStep(4);
      return;
    }
    if (step === 4) {
      void runFinish();
    }
  }, [step, runFinish]);
  const advancingRef = useRef(false);
  useInput(
    (_input, key) => {
      if (key.return && !advancingRef.current) {
        advancingRef.current = true;
        advanceFromCategory();
        setTimeout(() => {
          advancingRef.current = false;
        }, ADVANCE_GUARD_MS);
      }
    },
    { isActive: (step === 3 || step === 4) && !setupComplete }
  );
  if (setupComplete) {
    return /* @__PURE__ */ jsx(SetupComplete, { onDone });
  }
  if (step === 1) {
    return /* @__PURE__ */ jsx(WelcomeStep, { onNext: () => setStep(2), onSkip });
  }
  if (step === 2) {
    return /* @__PURE__ */ jsx(
      SystemStep,
      {
        onNext: () => setStep(3),
        onSkip,
        ...runSystemCheckImpl ? { runSystemCheckImpl } : {}
      }
    );
  }
  if (step === 3) {
    if (!llmCategory) {
      return /* @__PURE__ */ jsx(WelcomeStep, { onNext: () => setStep(4), onSkip });
    }
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
      /* @__PURE__ */ jsx(StepHeader, { step: 3 }),
      /* @__PURE__ */ jsx(
        CategoryScreen,
        {
          category: llmCategory,
          store,
          onBack: onSkip
        }
      ),
      /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u23CE continue \xB7 Esc to skip remaining steps" }) })
    ] });
  }
  if (!agentsCategory) {
    return /* @__PURE__ */ jsx(WelcomeStep, { onNext: onDone, onSkip });
  }
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(StepHeader, { step: 4 }),
    /* @__PURE__ */ jsx(
      CategoryScreen,
      {
        category: agentsCategory,
        store,
        onBack: onSkip
      }
    ),
    saving ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Saving\u2026" }) }) : null,
    saveError !== null ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: semantic.warn, children: saveError }) }) : null,
    /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u23CE Finish \xB7 Esc to skip and use defaults" }) })
  ] });
}
export {
  WizardSteps
};
//# sourceMappingURL=WizardSteps.js.map