All files / web/src/components/toys/euclid/engine replayConstruction.ts

0% Statements 0/408
0% Branches 0/1
0% Functions 0/1
0% Lines 0/408

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import type {
  ConstructionElement,
  PropositionStep,
  PropositionDef,
  ConstructionState,
  IntersectionCandidate,
  GhostLayer,
} from '../types'
import { needsExtendedSegments } from '../types'
import {
  initializeGiven,
  addSegment,
  addCircle,
  addPoint,
  getPoint,
  skipPointLabel,
} from './constructionState'
import { createFactStore, addFact, addAngleFact } from './factStore'
import type { FactStore } from './factStore'
import type { ProofFact } from './facts'
import { distancePair, angleMeasure } from './facts'
import { findNewIntersections } from './intersections'
import { deriveDef15Facts } from './factDerivation'
import { resolveSelector } from './selectors'
import { isCandidateBeyondPoint } from './intersections'
import { MACRO_REGISTRY } from './macros'

/**
 * A user action recorded after proposition completion.
 * These are replayed on top of the base construction during drag.
 */
export type PostCompletionAction =
  | { type: 'circle'; centerId: string; radiusPointId: string }
  | { type: 'segment'; fromId: string; toId: string }
  | { type: 'intersection'; ofA: string; ofB: string; which: number }
  | { type: 'macro'; propId: number; inputPointIds: string[]; atStep: number }
  /** A user-placed free point (playground mode). Dragging updates x/y in place. */
  | { type: 'free-point'; id: string; label: string; x: number; y: number }
  /** Post.2 extend: new point + segment beyond an existing segment endpoint */
  | {
      type: 'extend'
      baseId: string
      throughId: string
      pointId: string
      segmentId: string
      distance: number
    }

export interface ReplayResult {
  state: ConstructionState
  factStore: FactStore
  proofFacts: ProofFact[]
  candidates: IntersectionCandidate[]
  ghostLayers: GhostLayer[]
  /** Number of proposition steps that were successfully replayed.
   *  When less than the total step count, the construction broke down
   *  (e.g. an intersection no longer exists). */
  stepsCompleted: number
}

/**
 * Replay an entire construction from scratch given fresh given elements.
 * Executes all proposition steps in order, derives facts, runs conclusion
 * functions, then replays any post-completion user actions.
 *
 * Used by the drag interaction to recompute the full construction state
 * when given points are moved.
 */
export function replayConstruction(
  givenElements: ConstructionElement[],
  steps: PropositionStep[],
  propDef: PropositionDef,
  extraActions?: PostCompletionAction[],
  stepData?: Map<number, Record<string, unknown>>
): ReplayResult {
  let state = initializeGiven(givenElements)
  const factStore = createFactStore()
  let candidates: IntersectionCandidate[] = []
  const proofFacts: ProofFact[] = []
  const ghostLayers: GhostLayer[] = []
  const extendSegments = needsExtendedSegments(propDef)

  // Pre-load given facts
  if (propDef.givenFacts) {
    for (const gf of propDef.givenFacts) {
      const left = distancePair(gf.left.a, gf.left.b)
      const right = distancePair(gf.right.a, gf.right.b)
      const newFacts = addFact(factStore, left, right, { type: 'given' }, gf.statement, 'Given', -1)
      proofFacts.push(...newFacts)
    }
  }

  // Pre-load given angle facts
  if (propDef.givenAngleFacts) {
    for (const gaf of propDef.givenAngleFacts) {
      const left = angleMeasure(gaf.left.vertex, gaf.left.ray1, gaf.left.ray2)
      const right = angleMeasure(gaf.right.vertex, gaf.right.ray1, gaf.right.ray2)
      const newFacts = addAngleFact(
        factStore,
        left,
        right,
        { type: 'given' },
        gaf.statement,
        'Given',
        -1
      )
      proofFacts.push(...newFacts)
    }
  }

  // Execute each proposition step
  // For adaptive propositions, resolved overrides may replace expected actions
  const resolvedExpected = new Map<number, import('../types').ExpectedAction>()
  let stepsCompleted = 0
  for (let stepIdx = 0; stepIdx < steps.length; stepIdx++) {
    const step = steps[stepIdx]
    const expected = resolvedExpected.get(stepIdx) ?? step.expected

    let stepSucceeded = false

    if (expected.type === 'straightedge') {
      const result = addSegment(state, expected.fromId, expected.toId)
      state = result.state
      const newCands = findNewIntersections(state, result.segment, candidates, extendSegments)
      candidates = [...candidates, ...newCands]
      stepSucceeded = true
    } else if (expected.type === 'compass') {
      const result = addCircle(state, expected.centerId, expected.radiusPointId)
      state = result.state
      const newCands = findNewIntersections(state, result.circle, candidates, extendSegments)
      candidates = [...candidates, ...newCands]
      stepSucceeded = true
    } else if (expected.type === 'intersection') {
      // Find the matching candidate
      const resolvedA = expected.ofA != null ? resolveSelector(expected.ofA, state) : null
      const resolvedB = expected.ofB != null ? resolveSelector(expected.ofB, state) : null

      let matchingCandidate: IntersectionCandidate | undefined
      if (resolvedA && resolvedB) {
        const matching = candidates.filter(
          (c) =>
            (c.ofA === resolvedA && c.ofB === resolvedB) ||
            (c.ofA === resolvedB && c.ofB === resolvedA)
        )
        if (matching.length > 0) {
          if (expected.beyondId) {
            matchingCandidate = matching.find((c) =>
              isCandidateBeyondPoint(c, expected.beyondId!, c.ofA, c.ofB, state)
            )
          } else if (expected.label === 'C') {
            const pA = state.elements.find((e) => e.kind === 'point' && e.id === 'pt-A') as
              | { x: number; y: number }
              | undefined
            const pB = state.elements.find((e) => e.kind === 'point' && e.id === 'pt-B') as
              | { x: number; y: number }
              | undefined
            if (pA && pB) {
              const abx = pB.x - pA.x
              const aby = pB.y - pA.y
              const preferUpper = matching.filter(
                (c) => abx * (c.y - pA.y) - aby * (c.x - pA.x) > 0
              )
              matchingCandidate = preferUpper.length > 0 ? preferUpper[0] : matching[0]
            }
          }
          if (!matchingCandidate) {
            // When no beyondId, pick highest-Y candidate for stability.
            matchingCandidate = matching.reduce((best, c) => (c.y > best.y ? c : best), matching[0])
          }
        }
      } else if (expected.ofA == null && expected.ofB == null && candidates.length > 0) {
        // Wildcard intersection (no ofA/ofB specified)
        if (expected.label === 'C') {
          const pA = state.elements.find((e) => e.kind === 'point' && e.id === 'pt-A') as
            | { x: number; y: number }
            | undefined
          const pB = state.elements.find((e) => e.kind === 'point' && e.id === 'pt-B') as
            | { x: number; y: number }
            | undefined
          if (pA && pB) {
            const abx = pB.x - pA.x
            const aby = pB.y - pA.y
            const preferUpper = candidates.filter(
              (c) => abx * (c.y - pA.y) - aby * (c.x - pA.x) > 0
            )
            matchingCandidate = preferUpper.length > 0 ? preferUpper[0] : candidates[0]
          }
        }
        if (!matchingCandidate) {
          // Fallback: pick highest-Y candidate
          matchingCandidate = candidates.reduce(
            (best, c) => (c.y > best.y ? c : best),
            candidates[0]
          )
        }
      }

      if (matchingCandidate) {
        const result = addPoint(
          state,
          matchingCandidate.x,
          matchingCandidate.y,
          'intersection',
          expected.label
        )
        state = result.state
        candidates = candidates.filter(
          (c) =>
            !(
              Math.abs(c.x - matchingCandidate!.x) < 0.001 &&
              Math.abs(c.y - matchingCandidate!.y) < 0.001
            )
        )
        const newFacts = deriveDef15Facts(
          matchingCandidate,
          result.point.id,
          state,
          factStore,
          stepIdx
        )
        proofFacts.push(...newFacts)
        stepSucceeded = true
      } else {
        // Advance label/color indices so subsequent point labels stay stable
        state = skipPointLabel(state, expected.label)
      }
    } else if (expected.type === 'extend') {
      // Extend a line from baseId through throughId by a given distance
      const basePt = getPoint(state, expected.baseId)
      const throughPt = getPoint(state, expected.throughId)
      if (basePt && throughPt) {
        const dx = throughPt.x - basePt.x
        const dy = throughPt.y - basePt.y
        const len = Math.sqrt(dx * dx + dy * dy)
        if (len > 0.001) {
          const dirX = dx / len
          const dirY = dy / len
          // Resolve distance: explicit > stepData > segment length default
          const dist =
            expected.distance ?? (stepData?.get(stepIdx)?.distance as number | undefined) ?? len
          const newX = throughPt.x + dirX * dist
          const newY = throughPt.y + dirY * dist

          // Create the new point
          const ptResult = addPoint(state, newX, newY, 'intersection', expected.label)
          state = ptResult.state

          // Create the extension segment
          const segResult = addSegment(state, expected.throughId, ptResult.point.id)
          state = segResult.state

          // Find intersections for both
          const ptCands = findNewIntersections(state, ptResult.point, candidates, extendSegments)
          const segCands = findNewIntersections(
            state,
            segResult.segment,
            [...candidates, ...ptCands],
            extendSegments
          )
          candidates = [...candidates, ...ptCands, ...segCands]
          stepSucceeded = true
        }
      }
    } else if (expected.type === 'macro') {
      const macroDef = MACRO_REGISTRY[expected.propId]
      if (macroDef) {
        const result = macroDef.execute(
          state,
          expected.inputPointIds,
          candidates,
          factStore,
          stepIdx,
          extendSegments,
          expected.outputLabels
        )
        state = result.state
        candidates = result.candidates
        proofFacts.push(...result.newFacts)
        // Collect ghost layers produced by the macro itself
        for (const gl of result.ghostLayers) {
          ghostLayers.push({ ...gl, atStep: stepIdx })
        }
        stepSucceeded = true
      }
    }

    if (stepSucceeded) {
      stepsCompleted = stepIdx + 1
      // Resolve next step's expected action for adaptive propositions
      if (propDef.resolveStep && stepIdx + 1 < steps.length) {
        const override = propDef.resolveStep(stepIdx + 1, state, stepData ?? new Map())
        if (override?.expected) {
          resolvedExpected.set(stepIdx + 1, override.expected)
        }
      }
    }
  }

  // Run conclusion function
  const conclusionFn = propDef.deriveConclusion
  if (conclusionFn) {
    const conclusionFacts = conclusionFn(factStore, state, steps.length)
    proofFacts.push(...conclusionFacts)
  }

  // Replay post-completion user actions (always extend segments in freeform mode)
  if (extraActions) {
    // Recompute candidates with extension enabled for post-completion play
    if (!extendSegments) {
      for (const el of state.elements) {
        if (el.kind === 'point') continue
        const additional = findNewIntersections(state, el, candidates, true)
        candidates = [...candidates, ...additional]
      }
    }

    for (const action of extraActions) {
      if (action.type === 'circle') {
        const result = addCircle(state, action.centerId, action.radiusPointId)
        state = result.state
        const newCands = findNewIntersections(state, result.circle, candidates, true)
        candidates = [...candidates, ...newCands]
      } else if (action.type === 'segment') {
        const result = addSegment(state, action.fromId, action.toId)
        state = result.state
        const newCands = findNewIntersections(state, result.segment, candidates, true)
        candidates = [...candidates, ...newCands]
      } else if (action.type === 'intersection') {
        // Find matching candidate by parent elements and which-index
        const matching = candidates.find(
          (c) =>
            ((c.ofA === action.ofA && c.ofB === action.ofB) ||
              (c.ofA === action.ofB && c.ofB === action.ofA)) &&
            c.which === action.which
        )
        if (matching) {
          const result = addPoint(state, matching.x, matching.y, 'intersection')
          state = result.state
          candidates = candidates.filter(
            (c) => !(Math.abs(c.x - matching.x) < 0.001 && Math.abs(c.y - matching.y) < 0.001)
          )
          // Derive Def.15 facts for the new intersection point
          const newFacts = deriveDef15Facts(
            matching,
            result.point.id,
            state,
            factStore,
            steps.length
          )
          proofFacts.push(...newFacts)
        } else {
          // Advance label/color indices so subsequent point labels stay stable
          state = skipPointLabel(state)
        }
      } else if (action.type === 'macro') {
        const macroDef = MACRO_REGISTRY[action.propId]
        if (macroDef) {
          const macroResult = macroDef.execute(
            state,
            action.inputPointIds,
            candidates,
            factStore,
            action.atStep,
            true // extendSegments: always true for post-completion free-form
          )
          state = macroResult.state
          candidates = macroResult.candidates
          proofFacts.push(...macroResult.newFacts)
          for (const gl of macroResult.ghostLayers) {
            ghostLayers.push({ ...gl, atStep: action.atStep })
          }
        }
      } else if (action.type === 'free-point') {
        const result = addPoint(state, action.x, action.y, 'free', action.label)
        state = result.state
      } else if (action.type === 'extend') {
        // Replay extend: re-derive point position from base/through + stored distance
        const basePt = getPoint(state, action.baseId)
        const throughPt = getPoint(state, action.throughId)
        if (basePt && throughPt) {
          const dx = throughPt.x - basePt.x
          const dy = throughPt.y - basePt.y
          const len = Math.sqrt(dx * dx + dy * dy)
          if (len > 0.001) {
            const dirX = dx / len
            const dirY = dy / len
            const newX = throughPt.x + dirX * action.distance
            const newY = throughPt.y + dirY * action.distance
            const ptResult = addPoint(state, newX, newY, 'extend')
            state = ptResult.state
            const segResult = addSegment(state, action.throughId, ptResult.point.id)
            state = segResult.state
            const ptCands = findNewIntersections(state, ptResult.point, candidates, true)
            const segCands = findNewIntersections(
              state,
              segResult.segment,
              [...candidates, ...ptCands],
              true
            )
            candidates = [...candidates, ...ptCands, ...segCands]
          }
        }
      }
    }
  }

  return { state, factStore, proofFacts, candidates, ghostLayers, stepsCompleted }
}