import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";

const require = createRequire(import.meta.url);
const LighthouseEngine = require("../src/engine.js");
const LighthouseSave = require("../src/save.js");

const here = path.dirname(fileURLToPath(import.meta.url));
const story = JSON.parse(
  fs.readFileSync(path.join(here, "../../inputs/原创剧情.json"), "utf8")
);
const engine = LighthouseEngine.createEngine(story);
const KEY = LighthouseEngine.STORAGE_KEY;

let passed = 0;
const failures = [];

function test(name, fn) {
  try {
    fn();
    passed += 1;
    console.log(`ok ${passed} - ${name}`);
  } catch (error) {
    failures.push({ name, error });
    console.error(`not ok - ${name}`);
    console.error(error.stack || error);
  }
}

function enumeratePaths() {
  const paths = [];
  const walk = (nodeId, current) => {
    const node = engine.getNode(nodeId);
    if (typeof node.ending === "string") {
      paths.push(current.slice());
      return;
    }
    for (const choice of node.choices) {
      if (current.includes(choice.next)) {
        continue;
      }
      current.push(choice.next);
      walk(choice.next, current);
      current.pop();
    }
  };
  walk(engine.start, [engine.start]);
  return paths;
}

function playPath(startState, nodePath) {
  let current = startState;
  for (let index = 1; index < nodePath.length; index += 1) {
    current = engine.applyChoice(current, nodePath[index]);
    assert.ok(current, `choice ${nodePath[index - 1]} -> ${nodePath[index]} must be valid`);
  }
  return current;
}

function fakeStorage(initial = {}) {
  const map = new Map(Object.entries(initial));
  return {
    map,
    getItem(key) {
      return map.has(key) ? map.get(key) : null;
    },
    setItem(key, value) {
      map.set(key, String(value));
    },
    removeItem(key) {
      map.delete(key);
    }
  };
}

const paths = enumeratePaths();
const pathsByEnding = new Map();
for (const nodePath of paths) {
  const ending = engine.getNode(nodePath[nodePath.length - 1]).ending;
  if (!pathsByEnding.has(ending)) {
    pathsByEnding.set(ending, []);
  }
  pathsByEnding.get(ending).push(nodePath);
}

test("engine exposes the three original endings only", () => {
  assert.deepEqual(
    engine.endings.map((entry) => entry.name).sort(),
    ["归航", "守望", "真相"].sort()
  );
  assert.deepEqual(engine.nodeIds.sort(), Object.keys(story.nodes).sort());
});

test("fresh state has the documented v1 save structure", () => {
  const fresh = engine.freshState();
  assert.deepEqual(fresh, {
    schema: "cyberfete.d07.lighthouse",
    version: 1,
    current: "start",
    history: ["start"],
    endings: []
  });
  assert.equal(engine.serialize(fresh), JSON.stringify(fresh));
  assert.equal(engine.progress(fresh).found, 0);
  assert.equal(engine.progress(fresh).total, 3);
});

test("all root-to-ending paths are reachable and every choice edge is used", () => {
  assert.ok(paths.length >= 6, `expected at least 6 paths, got ${paths.length}`);
  assert.deepEqual(
    Array.from(pathsByEnding.keys()).sort(),
    ["归航", "守望", "真相"].sort()
  );
  for (const nodePath of paths) {
    let current = engine.freshState();
    current = playPath(current, nodePath);
    assert.deepEqual(current.history, nodePath);
    assert.equal(current.current, nodePath[nodePath.length - 1]);
    assert.equal(typeof engine.getNode(current.current).ending, "string");
  }

  const usedEdges = new Set();
  for (const nodePath of paths) {
    for (let index = 0; index < nodePath.length - 1; index += 1) {
      usedEdges.add(`${nodePath[index]}->${nodePath[index + 1]}`);
    }
  }
  for (const nodeId of engine.nodeIds) {
    const node = engine.getNode(nodeId);
    for (const choice of node.choices || []) {
      assert.ok(
        usedEdges.has(`${nodeId}->${choice.next}`),
        `edge ${nodeId}->${choice.next} is not on any start-to-ending path`
      );
    }
  }
});

test("collecting all three endings works across restarts", () => {
  let current = engine.freshState();
  for (const nodePath of paths) {
    current = engine.restart(current);
    const endingName = engine.getNode(nodePath[nodePath.length - 1]).ending;
    current = playPath(current, nodePath);
    assert.ok(current.endings.includes(endingName));
  }
  assert.deepEqual(current.endings.slice().sort(), ["归航", "守望", "真相"].sort());
  assert.equal(engine.progress(current).found, 3);
  assert.equal(engine.progress(current).percent, 100);
});

test("invalid choices are rejected without mutating state", () => {
  const state = engine.freshState();
  const before = JSON.stringify(state);
  assert.equal(engine.applyChoice(state, "sea"), null);
  assert.equal(engine.applyChoice(state, "missing"), null);
  assert.equal(engine.applyChoice(state, "start"), null);
  assert.equal(JSON.stringify(state), before);
});

test("ending nodes cannot be advanced from", () => {
  const endingState = playPath(engine.freshState(), ["start", "dock", "sea"]);
  assert.equal(engine.applyChoice(endingState, "home"), null);
  assert.equal(engine.getChoices(endingState.current).length, 0);
});

test("undo preserves collected endings and restores the previous location", () => {
  let state = playPath(engine.freshState(), ["start", "study", "cellar", "truth"]);
  assert.equal(state.current, "truth");
  const undone = engine.undo(state);
  assert.equal(undone.current, "cellar");
  assert.deepEqual(undone.history, ["start", "study", "cellar"]);
  assert.deepEqual(undone.endings, ["真相"]);
  assert.equal(engine.undo(engine.freshState()).history.length, 1);
});

test("restart preserves ending collection but resets the journey", () => {
  const state = playPath(engine.freshState(), ["start", "dock", "home"]);
  const restarted = engine.restart(state);
  assert.equal(restarted.current, "start");
  assert.deepEqual(restarted.history, ["start"]);
  assert.deepEqual(restarted.endings, ["守望"]);
});

test("clear removes progress and endings", () => {
  const state = playPath(engine.freshState(), ["start", "study", "cellar", "truth"]);
  assert.deepEqual(engine.clear().endings, []);
  assert.deepEqual(engine.clear().history, ["start"]);
  assert.deepEqual(engine.clear(), engine.freshState());
  assert.equal(state.endings.length, 1);
});

test("valid saves round-trip through serialize and validateSave", () => {
  let state = engine.freshState();
  state = playPath(state, ["start", "study", "cellar", "truth"]);
  const raw = engine.serialize(state);
  const result = engine.validateSave(raw);
  assert.equal(result.ok, true);
  assert.deepEqual(result.state, state);
  assert.notEqual(result.state.history, state.history);
  result.state.history.push("tampered");
  assert.equal(state.history.length, 4);
});

test("collected endings may survive a restart in a valid save", () => {
  const state = {
    ...engine.freshState(),
    endings: ["归航", "真相"]
  };
  const result = engine.validateSave(state);
  assert.equal(result.ok, true);
  assert.deepEqual(result.state.endings, ["归航", "真相"]);
});

test("validateSave classifies malformed and legacy saves", () => {
  const fresh = engine.freshState();
  const cases = [
    ["{bad json", "json"],
    ["null", "shape"],
    ["42", "shape"],
    [[], "shape"],
    [{ ...fresh, version: 0 }, "version"],
    [{ ...fresh, schema: "legacy.schema" }, "schema"],
    [{ ...fresh, current: "nowhere" }, "current"],
    [{ ...fresh, history: [] }, "history"],
    [{ ...fresh, history: ["dock"] }, "history-start"],
    [{ ...fresh, history: ["start", "dock"] }, "history-current"],
    [{ ...fresh, current: "sea", history: ["start", "sea"] }, "path"],
    [{ ...fresh, endings: "归航" }, "endings"],
    [{ ...fresh, endings: ["归航", "归航"] }, "endings"],
    [{ ...fresh, endings: ["不存在"] }, "endings"],
    [{ ...fresh, current: "SEA", history: ["start", "dock", "sea"], endings: [] }, "current"],
    [{ ...fresh, current: "sea", history: ["start", "dock", "sea"], endings: [] }, "ending-missing"],
    [{ ...fresh, extra: true }, "shape"]
  ];

  for (const [raw, expectedReason] of cases) {
    const result = engine.validateSave(raw);
    assert.equal(result.ok, false, `expected invalid: ${JSON.stringify(raw)}`);
    assert.equal(result.reason, expectedReason, `reason for ${JSON.stringify(raw)}`);
  }
});

test("valid ending save is accepted with its ending recorded", () => {
  const state = playPath(engine.freshState(), ["start", "dock", "sea"]);
  const result = engine.validateSave(state);
  assert.equal(result.ok, true);
  assert.deepEqual(result.state.endings, ["归航"]);
});

test("save manager reports unavailable storage without throwing", () => {
  const manager = LighthouseSave.createSaveManager(null, engine);
  assert.equal(manager.isAvailable(), false);
  const read = manager.read();
  assert.equal(read.storage, false);
  assert.equal(read.reason, "unavailable");
  assert.deepEqual(read.state, engine.freshState());
  assert.equal(manager.write(engine.freshState()), false);
  assert.equal(manager.clear(), false);
});

test("save manager writes and restores a valid session", () => {
  const storage = fakeStorage();
  const manager = LighthouseSave.createSaveManager(storage, engine);
  assert.equal(manager.read().restored, false);
  assert.equal(manager.read().reset, false);

  const state = playPath(engine.freshState(), ["start", "study", "cellar", "truth"]);
  assert.equal(manager.write(state), true);
  assert.ok(storage.map.has(KEY));

  const restored = manager.read();
  assert.equal(restored.restored, true);
  assert.equal(restored.reset, false);
  assert.deepEqual(restored.state, state);
});

test("save manager safely resets an old-version save and removes it", () => {
  const old = { ...engine.freshState(), version: 0, endings: ["归航"] };
  const storage = fakeStorage({ [KEY]: JSON.stringify(old) });
  const manager = LighthouseSave.createSaveManager(storage, engine);
  const read = manager.read();
  assert.equal(read.reset, true);
  assert.equal(read.reason, "version");
  assert.deepEqual(read.state, engine.freshState());
  assert.equal(storage.map.has(KEY), false);
});

test("save manager safely resets corrupt JSON and invalid paths", () => {
  const corruptStorage = fakeStorage({ [KEY]: "{not-json" });
  const corrupt = LighthouseSave.createSaveManager(corruptStorage, engine).read();
  assert.equal(corrupt.reset, true);
  assert.equal(corrupt.reason, "json");
  assert.equal(corruptStorage.map.has(KEY), false);

  const invalid = {
    ...engine.freshState(),
    current: "sea",
    history: ["start", "sea"]
  };
  const pathStorage = fakeStorage({ [KEY]: JSON.stringify(invalid) });
  const pathRead = LighthouseSave.createSaveManager(pathStorage, engine).read();
  assert.equal(pathRead.reset, true);
  assert.equal(pathRead.reason, "path");
  assert.equal(pathStorage.map.has(KEY), false);
});

test("save manager handles storage exceptions", () => {
  const throwingRead = {
    getItem() {
      throw new Error("blocked");
    },
    setItem() {},
    removeItem() {}
  };
  const manager = LighthouseSave.createSaveManager(throwingRead, engine);
  const read = manager.read();
  assert.equal(read.reason, "storage-error");
  assert.equal(read.storage, false);
  assert.equal(manager.isAvailable(), false);

  const throwingWrite = fakeStorage();
  throwingWrite.setItem = () => {
    throw new Error("quota");
  };
  const writeManager = LighthouseSave.createSaveManager(throwingWrite, engine);
  assert.equal(writeManager.write(engine.freshState()), false);
  assert.equal(writeManager.isAvailable(), false);
});

test("clear removes the stored save", () => {
  const storage = fakeStorage();
  const manager = LighthouseSave.createSaveManager(storage, engine);
  manager.write(engine.freshState());
  assert.equal(storage.map.has(KEY), true);
  assert.equal(manager.clear(), true);
  assert.equal(storage.map.has(KEY), false);
});

if (failures.length > 0) {
  console.error(`\n${failures.length} test(s) failed, ${passed} passed.`);
  process.exitCode = 1;
} else {
  console.log(`\n${passed} tests passed.`);
}
