import { BlockGeometry } from "./block-features";

/**
 * Geometry is an OPTIONAL signal, injected through this interface so the
 * classifier and segmenter can run identically under jsdom (no layout) and
 * in a real browser. See classify-block.ts: every geometry-derived weight is
 * capped so it can never cross a threshold alone.
 */
export interface GeometryProvider {
  measure(el: Element): BlockGeometry | undefined;
  documentTextLength(): number;
}

/** Used under jsdom / whenever layout is unavailable. */
export const NullGeometryProvider: GeometryProvider = {
  measure() {
    return undefined;
  },
  documentTextLength() {
    return 0;
  },
};

const ROW_LAYOUT_DISPLAYS = new Set(["flex", "inline-flex", "grid", "inline-grid"]);

/**
 * Real browser implementation. `measure()` must only be called after all
 * DOM reads for a segmentation pass have been decided (batched, no
 * interleaved writes) — see segment-page.ts's single measurement burst.
 */
export class DomGeometryProvider implements GeometryProvider {
  private _docTextLength: number | undefined;

  public measure(el: Element): BlockGeometry | undefined {
    if (!(el instanceof HTMLElement)) return undefined;
    const rect = el.getBoundingClientRect();
    const styles = window.getComputedStyle(el);
    const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    const cssPosition = styles.position;
    const display = styles.display;
    return {
      top: rect.top,
      left: rect.left,
      width: rect.width,
      height: rect.height,
      viewportWidth,
      viewportHeight,
      cssPosition,
      overflowX: styles.overflowX,
      zIndex: Number.parseInt(styles.zIndex, 10) || 0,
      isSticky: cssPosition === "fixed" || cssPosition === "sticky",
      isAboveFold: rect.top < viewportHeight,
      isFullWidth: rect.width >= 0.9 * viewportWidth,
      isNarrowColumn: rect.width <= 0.35 * viewportWidth && rect.height > 200,
      isRowLayout:
        ROW_LAYOUT_DISPLAYS.has(display) &&
        (styles.flexDirection === "row" || styles.flexDirection === "" || display.includes("grid")),
      scrollsHorizontally: el.scrollWidth > el.clientWidth * 1.2,
    };
  }

  public documentTextLength(): number {
    if (this._docTextLength == undefined) {
      this._docTextLength = (document.body?.textContent || "").trim().length;
    }
    return this._docTextLength;
  }
}

/**
 * Test double. Reads a `data-test-rect="top,left,w,h"` attribute baked into
 * jsdom fixtures so geometry-dependent rules can be exercised without a
 * browser. See tests/reader/structure — the parity invariant test compares
 * NullGeometryProvider vs FakeGeometryProvider output and fails if a weight
 * tweak accidentally makes geometry decisive on its own.
 */
export class FakeGeometryProvider implements GeometryProvider {
  private _viewportWidth: number;
  private _viewportHeight: number;
  private _docTextLength: number;

  constructor(opts: { viewportWidth?: number; viewportHeight?: number; documentTextLength?: number } = {}) {
    this._viewportWidth = opts.viewportWidth ?? 1280;
    this._viewportHeight = opts.viewportHeight ?? 800;
    this._docTextLength = opts.documentTextLength ?? 0;
  }

  public measure(el: Element): BlockGeometry | undefined {
    const raw = el.getAttribute("data-test-rect");
    if (raw == undefined) return undefined;
    const [top, left, width, height] = raw.split(",").map(Number);
    const cssPosition = el.getAttribute("data-test-position") || "static";
    const overflowX = el.getAttribute("data-test-overflow-x") || "visible";
    const isRowLayout = el.getAttribute("data-test-row-layout") === "true";
    const zIndex = Number.parseInt(el.getAttribute("data-test-zindex") || "0", 10) || 0;
    return {
      top,
      left,
      width,
      height,
      viewportWidth: this._viewportWidth,
      viewportHeight: this._viewportHeight,
      cssPosition,
      overflowX,
      zIndex,
      isSticky: cssPosition === "fixed" || cssPosition === "sticky",
      isAboveFold: top < this._viewportHeight,
      isFullWidth: width >= 0.9 * this._viewportWidth,
      isNarrowColumn: width <= 0.35 * this._viewportWidth && height > 200,
      isRowLayout,
      scrollsHorizontally: overflowX === "auto" || overflowX === "scroll",
    };
  }

  public documentTextLength(): number {
    return this._docTextLength;
  }
}
