/**
 * Robot grid simulator — language, parser, and interpreter.
 *
 * This module is intentionally free of Node/DOM APIs so the exact same engine
 * runs in the browser (instant visual feedback) and on the server (authoritative
 * scoring that a student cannot forge).
 *
 * Language
 * --------
 *   move()            step one cell forward
 *   turnLeft()        rotate 90° counter-clockwise
 *   turnRight()       rotate 90° clockwise
 *   pick()            collect a star on the current cell
 *   repeat(n) { ... } repeat a block n times
 *   if (starHere()) { ... }   conditional block
 *   else { ... }
 *
 * Program errors carry a line number so the editor can point at the mistake.
 */

export type Direction = "north" | "east" | "south" | "west";

export const DIRECTIONS: Direction[] = ["north", "east", "south", "west"];

/** Clockwise turn order, used to rotate headings. */
const TURN_RIGHT: Record<Direction, Direction> = {
  north: "east",
  east: "south",
  south: "west",
  west: "north",
};

const TURN_LEFT: Record<Direction, Direction> = {
  north: "west",
  west: "south",
  south: "east",
  east: "north",
};

const DELTA: Record<Direction, { dx: number; dy: number }> = {
  north: { dx: 0, dy: -1 },
  east: { dx: 1, dy: 0 },
  south: { dx: 0, dy: 1 },
  west: { dx: -1, dy: 0 },
};

export const DIRECTION_LABELS: Record<Direction, string> = {
  north: "Utara",
  east: "Timur",
  south: "Selatan",
  west: "Barat",
};

export interface GridPoint {
  x: number;
  y: number;
}

export interface SimulatorConfig {
  gridWidth: number;
  gridHeight: number;
  /** Impassable cells, encoded as `[x, y]` pairs. */
  walls: [number, number][];
  startX: number;
  startY: number;
  startDir: Direction;
  goalX: number;
  goalY: number;
  /** Collectable stars, encoded as `[x, y]` pairs. */
  stars: [number, number][];
  maxSteps: number;
}

export interface TraceFrame {
  /** Step index, starting at 1. */
  step: number;
  action: string;
  x: number;
  y: number;
  dir: Direction;
  collected: GridPoint[];
  blocked: boolean;
  note: string;
}

export interface SimulatorResult {
  success: boolean;
  reachedGoal: boolean;
  stepsUsed: number;
  starsCollected: number;
  totalStars: number;
  parSteps: number;
  score: number;
  trace: TraceFrame[];
  error: string | null;
  errorLine: number | null;
  message: string;
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

type Statement =
  | { kind: "command"; name: string; line: number }
  | { kind: "repeat"; times: number; body: Statement[]; line: number }
  | { kind: "if"; condition: string; then: Statement[]; otherwise: Statement[]; line: number };

interface Token {
  type: "ident" | "number" | "punct";
  value: string;
  line: number;
}

export class ProgramError extends Error {
  line: number;
  constructor(message: string, line: number) {
    super(message);
    this.name = "ProgramError";
    this.line = line;
  }
}

const SIMPLE_COMMANDS: Record<string, true> = {
  move: true,
  turnLeft: true,
  turnRight: true,
  pick: true,
};

const CONDITIONS: Record<string, true> = {
  starHere: true,
  goalHere: true,
  canMove: true,
  pathClear: true,
};

function tokenize(source: string): Token[] {
  const tokens: Token[] = [];
  const lines = source.split(/\r?\n/);

  for (let index = 0; index < lines.length; index += 1) {
    const lineNo = index + 1;
    const raw = lines[index];
    // Strip line comments before scanning.
    const text = raw.replace(/\/\/.*$/, "").replace(/#.*$/, "");
    const pattern = /\s*([A-Za-z_][A-Za-z0-9_]*|\d+|[{}()])/g;
    let match: RegExpExecArray | null;
    while ((match = pattern.exec(text)) !== null) {
      const value = match[1];
      const type = /^\d+$/.test(value) ? "number" : /^[A-Za-z_]/.test(value) ? "ident" : "punct";
      tokens.push({ type, value, line: lineNo });
    }
  }

  return tokens;
}

function parseProgram(source: string): Statement[] {
  const tokens = tokenize(source);
  let cursor = 0;

  function peek(): Token | undefined {
    return tokens[cursor];
  }

  function next(): Token {
    const token = tokens[cursor];
    if (!token) {
      const last = tokens[tokens.length - 1];
      throw new ProgramError("Program ended unexpectedly — a closing brace is missing.", last?.line ?? 1);
    }
    cursor += 1;
    return token;
  }

  function expect(value: string) {
    const token = next();
    if (token.value !== value) {
      throw new ProgramError(`Expected "${value}" but found "${token.value}".`, token.line);
    }
  }

  function parseBlock(): Statement[] {
    expect("{");
    const statements: Statement[] = [];
    while (peek() && peek()!.value !== "}") {
      statements.push(parseStatement());
    }
    expect("}");
    return statements;
  }

  function parseStatement(): Statement {
    const token = next();

    if (token.value === "repeat") {
      expect("(");
      const count = next();
      if (count.type !== "number") {
        throw new ProgramError('repeat() needs a whole number, e.g. repeat(4) { ... }.', count.line);
      }
      expect(")");
      const times = Number.parseInt(count.value, 10);
      if (times < 0 || times > 500) {
        throw new ProgramError("repeat() count must be between 0 and 500.", count.line);
      }
      return { kind: "repeat", times, body: parseBlock(), line: token.line };
    }

    if (token.value === "if") {
      expect("(");
      const conditionToken = next();
      if (conditionToken.type !== "ident" || !CONDITIONS[conditionToken.value]) {
        throw new ProgramError(
          `Unknown condition "${conditionToken.value}". Try starHere(), goalHere(), canMove() or pathClear().`,
          conditionToken.line
        );
      }
      expect(")");
      const then = parseBlock();
      let otherwise: Statement[] = [];
      if (peek()?.value === "else") {
        next();
        otherwise = parseBlock();
      }
      return { kind: "if", condition: conditionToken.value, then, otherwise, line: token.line };
    }

    if (token.type !== "ident" || !SIMPLE_COMMANDS[token.value]) {
      throw new ProgramError(
        `Unknown command "${token.value}". Available: move(), turnLeft(), turnRight(), pick(), repeat(), if().`,
        token.line
      );
    }

    // Command invocation must be written as name().
    if (peek()?.value !== "(") {
      throw new ProgramError(`Did you mean ${token.value}()? Commands need parentheses.`, token.line);
    }
    next();
    expect(")");
    return { kind: "command", name: token.value, line: token.line };
  }

  const program: Statement[] = [];
  while (cursor < tokens.length) {
    program.push(parseStatement());
  }
  if (program.length === 0) {
    throw new ProgramError("The program is empty. Add at least one command, e.g. move().", 1);
  }
  return program;
}

// ---------------------------------------------------------------------------
// Interpreter
// ---------------------------------------------------------------------------

interface MachineState {
  x: number;
  y: number;
  dir: Direction;
  steps: number;
  collected: GridPoint[];
  trace: TraceFrame[];
}

export function runSimulator(program: string, config: SimulatorConfig): SimulatorResult {
  const wallKeys = new Set(config.walls.map(([x, y]) => `${x},${y}`));
  const starKeys = new Set(config.stars.map(([x, y]) => `${x},${y}`));
  const totalStars = config.stars.length;

  const state: MachineState = {
    x: config.startX,
    y: config.startY,
    dir: config.startDir,
    steps: 0,
    collected: [],
    trace: [
      {
        step: 0,
        action: "start",
        x: config.startX,
        y: config.startY,
        dir: config.startDir,
        collected: [],
        blocked: false,
        note: "Robot siap",
      },
    ],
  };

  const inside = (x: number, y: number) =>
    x >= 0 && y >= 0 && x < config.gridWidth && y < config.gridHeight;

  const blockedAt = (x: number, y: number) => !inside(x, y) || wallKeys.has(`${x},${y}`);

  const ahead = () => {
    const { dx, dy } = DELTA[state.dir];
    return { x: state.x + dx, y: state.y + dy };
  };

  const push = (action: string, blocked: boolean, note: string) => {
    state.trace.push({
      step: state.steps,
      action,
      x: state.x,
      y: state.y,
      dir: state.dir,
      collected: [...state.collected],
      blocked,
      note,
    });
  };

  function budgetExceeded(): boolean {
    if (state.steps >= config.maxSteps) {
      throw new ProgramError(
        `Step limit reached (${config.maxSteps}). Is the robot looping forever?`,
        0
      );
    }
    return false;
  }

  function execute(statements: Statement[]) {
    for (const statement of statements) {
      if (statement.kind === "command") {
        if (budgetExceeded()) return;
        switch (statement.name) {
          case "move": {
            const target = ahead();
            if (blockedAt(target.x, target.y)) {
              state.steps += 1;
              push("move", true, "Menabrak dinding");
            } else {
              state.x = target.x;
              state.y = target.y;
              state.steps += 1;
              push("move", false, `Bergerak ke (${state.x}, ${state.y})`);
            }
            break;
          }
          case "turnLeft":
            state.dir = TURN_LEFT[state.dir];
            state.steps += 1;
            push("turnLeft", false, `Menghadap ${DIRECTION_LABELS[state.dir]}`);
            break;
          case "turnRight":
            state.dir = TURN_RIGHT[state.dir];
            state.steps += 1;
            push("turnRight", false, `Menghadap ${DIRECTION_LABELS[state.dir]}`);
            break;
          case "pick": {
            const key = `${state.x},${state.y}`;
            if (starKeys.has(key) && !state.collected.some((p) => p.x === state.x && p.y === state.y)) {
              state.collected.push({ x: state.x, y: state.y });
              state.steps += 1;
              push("pick", false, "Bintang diambil");
            } else {
              state.steps += 1;
              push("pick", false, "Tidak ada bintang di sini");
            }
            break;
          }
          default:
            break;
        }
      } else if (statement.kind === "repeat") {
        for (let i = 0; i < statement.times; i += 1) {
          execute(statement.body);
        }
      } else {
        const { x, y } = ahead();
        const starHere = starKeys.has(`${state.x},${state.y}`);
        const goalHere = state.x === config.goalX && state.y === config.goalY;
        let outcome: boolean;
        switch (statement.condition) {
          case "starHere":
            outcome = starHere;
            break;
          case "goalHere":
            outcome = goalHere;
            break;
          case "canMove":
            outcome = !blockedAt(x, y);
            break;
          case "pathClear":
            outcome = !blockedAt(x, y) && !wallKeys.has(`${x},${y}`);
            break;
          default:
            outcome = false;
        }
        execute(outcome ? statement.then : statement.otherwise);
      }
    }
  }

  let error: string | null = null;
  let errorLine: number | null = null;

  try {
    const ast = parseProgram(program);
    execute(ast);
  } catch (caught) {
    if (caught instanceof ProgramError) {
      error = caught.message;
      errorLine = caught.line > 0 ? caught.line : null;
    } else {
      error = caught instanceof Error ? caught.message : "Unknown execution error.";
    }
  }

  const reachedGoal = state.x === config.goalX && state.y === config.goalY;
  const starsCollected = state.collected.length;
  const success = error === null && reachedGoal && starsCollected === totalStars;

  // Score: reward completion, star collection and efficiency relative to par.
  let score = 0;
  if (reachedGoal) score += 50;
  if (totalStars > 0) score += Math.round((starsCollected / totalStars) * 30);
  if (success) {
    const par = Math.max(1, config.maxSteps * 0.4);
    const efficiency = Math.max(0, Math.min(1, par / Math.max(1, state.steps)));
    score += Math.round(efficiency * 20);
  }
  if (error) score = Math.max(0, score - 10);

  let message: string;
  if (error) {
    message = "Program berhenti karena error.";
  } else if (success) {
    message = "Berhasil! Robot mencapai tujuan dan mengambil semua bintang.";
  } else if (reachedGoal) {
    message = `Robot mencapai tujuan, tetapi baru mengambil ${starsCollected} dari ${totalStars} bintang.`;
  } else {
    message = "Robot belum mencapai tujuan.";
  }

  return {
    success,
    reachedGoal,
    stepsUsed: state.steps,
    starsCollected,
    totalStars,
    parSteps: config.maxSteps,
    score: Math.max(0, Math.min(100, score)),
    trace: state.trace,
    error,
    errorLine,
    message,
  };
}

/** Parse a stored challenge's JSON columns into a typed config. */
export function configFromChallenge(challenge: {
  gridWidth: number;
  gridHeight: number;
  walls: unknown;
  startX: number;
  startY: number;
  startDir: string;
  goalX: number;
  goalY: number;
  stars: unknown;
  maxSteps: number;
}): SimulatorConfig {
  const toPairs = (value: unknown): [number, number][] => {
    if (!Array.isArray(value)) return [];
    return value
      .filter(
        (item): item is [number, number] =>
          Array.isArray(item) && item.length === 2 && typeof item[0] === "number" && typeof item[1] === "number"
      )
      .map((item) => [item[0], item[1]] as [number, number]);
  };

  const dir = (DIRECTIONS as string[]).includes(challenge.startDir)
    ? (challenge.startDir as Direction)
    : "east";

  return {
    gridWidth: challenge.gridWidth,
    gridHeight: challenge.gridHeight,
    walls: toPairs(challenge.walls),
    startX: challenge.startX,
    startY: challenge.startY,
    startDir: dir,
    goalX: challenge.goalX,
    goalY: challenge.goalY,
    stars: toPairs(challenge.stars),
    maxSteps: challenge.maxSteps,
  };
}
