// src/framework/shadowlisp/primitives/SlCar.ts
//
// Vision 49: Car element - first of list - IS a Matrix component
//
// John McCarthy (LISP creator, Turing Award 1971):
//   "CAR originally stood for 'Contents of Address Register' on the IBM 704.
//    It returns the first element of a cons cell."
//
// <sl-car><list></sl-car> => first element of list

import type { SExpr } from '../../../lisp/SExpr';
import { SlMatrixElement } from '../SlMatrixElement';
import { SlBootstrap } from '../SlBootstrap';

/**
 * SlCar - Car element (McCarthy primitive #4) that IS a Matrix component.
 *
 * Returns the first element of a list.
 *
 * @example
 * <sl-car><sl-list><sl-num>1</sl-num><sl-num>2</sl-num></sl-list></sl-car>  => 1
 */
export class SlCar extends SlMatrixElement {
  /**
   * Evaluate the child and return its first element.
   */
  async evalSelf(env: SExpr[]): Promise<SExpr> {
    const child = this.firstElementChild;
    if (!child) {
      throw new Error('sl-car requires a child element');
    }

    // Evaluate the child to get the list
    const list = await this.evalChild(child, env);

    // Apply car
    return SlBootstrap.car(list);
  }

  toSExpr(): SExpr {
    const child = this.firstElementChild;
    if (!child || !(child instanceof SlMatrixElement)) {
      return ['car', null];
    }
    return ['car', child.toSExpr()];
  }
}

if (!customElements.get('sl-car')) {
  customElements.define('sl-car', SlCar);
}
