import { useMemo } from "react";
import {
  AJZ_MACHINE_MIME,
  buildPageMachineManifest,
  encodeAjzMachinePayload,
} from "./machineTagCodec";

/**
 * 隐藏机器标签：DOM 中非明文承载当前页 API 契约，用户看不见。
 * AI/爬虫选取：
 *   document.querySelector('[data-ajz-machine][data-ajz-kind="page"]')
 * 解码：decodeAjzMachinePayload(el.getAttribute('data-ajz-machine'))
 */
export function PageMachineTag(props: {
  slug: string;
  resource: string;
  page: { id: string; type: string; route: string; title: string; entity: string; layout?: any };
  blueprint: any;
}) {
  const payload = useMemo(() => {
    try {
      const manifest = buildPageMachineManifest(props);
      return encodeAjzMachinePayload(manifest);
    } catch {
      return "";
    }
  }, [props.slug, props.resource, props.page?.id, props.page?.type, props.page?.entity, props.blueprint]);

  if (!payload) return null;

  return (
    <div
      className="ajz-machine-tag"
      hidden
      aria-hidden="true"
      data-ajz-machine={payload}
      data-ajz-mime={AJZ_MACHINE_MIME}
      data-ajz-codec="AJZP1"
      data-ajz-kind="page"
      data-ajz-slug={props.slug}
      data-ajz-page={props.page.id}
      data-ajz-entity={props.page.entity}
      data-ajz-resource={props.resource}
    />
  );
}

/** 区块级标签（看板各数据区），同样非明文。 */
export function BlockMachineTag(props: {
  slug: string;
  resource: string;
  blockId: string;
  endpoint?: { method: string; path: string };
  extra?: Record<string, unknown>;
}) {
  const payload = useMemo(() => {
    try {
      return encodeAjzMachinePayload({
        v: 1,
        kind: "ajz-block",
        slug: props.slug,
        resource: props.resource,
        block_id: props.blockId,
        endpoint: props.endpoint || {
          method: "GET",
          path: `/api/v1/apps/${props.slug}/${props.resource}`,
        },
        ...(props.extra || {}),
      });
    } catch {
      return "";
    }
  }, [props.slug, props.resource, props.blockId, props.endpoint, props.extra]);

  if (!payload) return null;
  return (
    <div
      className="ajz-machine-tag"
      hidden
      aria-hidden="true"
      data-ajz-machine={payload}
      data-ajz-mime={AJZ_MACHINE_MIME}
      data-ajz-codec="AJZP1"
      data-ajz-kind="block"
      data-ajz-block={props.blockId}
      data-ajz-slug={props.slug}
      data-ajz-resource={props.resource}
    />
  );
}
