import * as cp from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { Project } from "ts-morph";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
  EITRI_FORMAT_ALIASES,
  WIDGET_TYPE_FORMATS,
  applyWidgetFormat,
  beautify,
  definitionIdForPath,
  normalizeFormats,
  typeToJsonSchema,
} from "./generate-schema";

describe("definitionIdForPath", () => {
  it("is repo-relative, never absolute", () => {
    const id = definitionIdForPath(
      "/Users/anyone/code/mysite/src/sections/Hero.tsx",
      "/Users/anyone/code/mysite",
    );
    expect(Buffer.from(id, "base64").toString()).toBe("src/sections/Hero.tsx");
  });

  it("normalizes file:// prefixes from ts-morph", () => {
    const id = definitionIdForPath(
      "file:///Users/anyone/code/mysite/src/sections/Hero.tsx",
      "/Users/anyone/code/mysite",
    );
    expect(Buffer.from(id, "base64").toString()).toBe("src/sections/Hero.tsx");
  });
});

describe("normalizeFormats (Eitri @format aliases)", () => {
  it("remaps a known alias in a nested prop schema", () => {
    const defs = {
      "abc@Props": {
        type: "object",
        properties: {
          datetime: { type: "string", format: "datetime", title: "Publish date." },
          post: { type: "string", format: "textarea" },
        },
      },
    };
    normalizeFormats(defs, EITRI_FORMAT_ALIASES);
    expect(defs["abc@Props"].properties.datetime.format).toBe("date-time");
    // textarea is already a valid widget format — left untouched.
    expect(defs["abc@Props"].properties.post.format).toBe("textarea");
  });

  it("recurses through arrays and leaves unknown formats alone", () => {
    const node = {
      items: [{ format: "datetime" }, { format: "email" }],
    };
    normalizeFormats(node, EITRI_FORMAT_ALIASES);
    expect(node.items[0].format).toBe("date-time");
    expect(node.items[1].format).toBe("email");
  });

  it("is a no-op on primitives / null", () => {
    expect(() => normalizeFormats(null, EITRI_FORMAT_ALIASES)).not.toThrow();
    expect(() => normalizeFormats("datetime", EITRI_FORMAT_ALIASES)).not.toThrow();
  });
});

describe("applyWidgetFormat", () => {
  it("recovers an unresolved widget alias (empty schema) as string + format", () => {
    // When a widget alias like `Color` is imported from a module ts-morph can't
    // resolve (remote/CDN), the type comes through as `any` and typeToJsonSchema
    // returns {}. The intended widget must still be recovered.
    const schema: any = {};
    applyWidgetFormat(schema, "Color");
    expect(schema).toEqual({ type: "string", format: "color-input" });
  });

  it.each(Object.entries(WIDGET_TYPE_FORMATS))(
    "recovers the %s alias to { type: string, format: %s } from an empty schema",
    (alias, format) => {
      const schema: any = {};
      applyWidgetFormat(schema, alias);
      expect(schema).toEqual({ type: "string", format });
    },
  );

  it("applies the format to a resolved string schema", () => {
    const schema: any = { type: "string" };
    applyWidgetFormat(schema, "Color");
    expect(schema).toEqual({ type: "string", format: "color-input" });
  });

  it("does not overwrite a schema that resolved to a $ref", () => {
    const schema: any = { $ref: "#/definitions/Foo" };
    applyWidgetFormat(schema, "Color");
    expect(schema).toEqual({ $ref: "#/definitions/Foo" });
  });

  it("does not touch a schema for a non-widget type hint", () => {
    const schema: any = {};
    applyWidgetFormat(schema, "SomeRandomType");
    expect(schema).toEqual({});
  });
});

describe("typeToJsonSchema with an unresolvable widget alias import", () => {
  it("emits { type: string, format: color-input } for a Color field imported from a CDN", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true, noResolve: false },
    });

    // The import target is not resolvable, mirroring apps that import `Color`
    // from a remote deco-cx/apps CDN URL — `Color` therefore resolves to `any`.
    const sf = project.createSourceFile(
      "props.ts",
      `
        import type { Color } from "https://cdn.example.com/admin/widgets.ts";

        export interface Props {
          /** @title Cor do Texto */
          textLeftColor?: Color;
        }
      `,
    );

    const propsType = sf.getInterfaceOrThrow("Props").getType();
    const schema = typeToJsonSchema(propsType);

    expect(schema.type).toBe("object");
    expect(schema.properties.textLeftColor).toEqual({
      title: "Cor do Texto",
      type: "string",
      format: "color-input",
    });
  }, 30_000);
});

describe("typeToJsonSchema with intersection types", () => {
  it("keeps a branded primitive (`string & { __brand }`) as a string", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true },
    });
    const sf = project.createSourceFile(
      "props.ts",
      `
        type Slug = string & { readonly __brand: unique symbol };
        export interface Props { slug?: Slug }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.slug.type).toBe("string");
  }, 30_000);

  it("expands an object intersection into a merged field set (recursive menu shape)", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true },
    });
    // Mirrors a production header `SiteNavigationElement` recursive workaround:
    // nested children written as `Leaf & { children?: Array<…> }`. Before the
    // intersection branch these collapsed to `children: { items: { type: "string" } }`.
    const sf = project.createSourceFile(
      "props.ts",
      `
        interface Leaf {
          /** The name of the item. */
          name?: string;
          /** URL of the item. */
          url?: string;
        }
        export interface Props {
          navItems?: Array<
            Leaf & {
              children?: Array<Leaf & { children?: Leaf[] }>;
            }
          >;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());

    const item = schema.properties.navItems.items;
    expect(item.type).toBe("object");
    expect(Object.keys(item.properties).sort()).toEqual(["children", "name", "url"]);

    const child = item.properties.children.items;
    expect(child.type).toBe("object");
    expect(child.properties.name.type).toBe("string");
    expect(child.properties.url.type).toBe("string");
    expect(child.properties.children.items.type).toBe("object");
  }, 30_000);
});

// Sites compile with `strict`, so an optional prop is `T | undefined` (nullable).
function strictProject() {
  return new Project({
    useInMemoryFileSystem: true,
    compilerOptions: { skipLibCheck: true, strict: true },
  });
}

describe("typeToJsonSchema underscore-prefixed props", () => {
  it("keeps `__title` and `_id` (admin label, dynamic-options key) but not __resolveType", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/props.ts",
      `
        /** @title {{__title}} */
        export interface Rule {
          /**
           * @title Título (opcional)
           * @description Título do CMS.
           */
          __title?: string;
          /**
           * @title Regulamento
           * @format dynamic-options
           * @options site/loaders/admin/regulation.ts
           */
          _id?: string;
          __resolveType?: string;
          pathname: string;
        }
        export interface Props { rules: Rule[] }
      `,
    );
    const item = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType()).properties.rules.items;
    expect(Object.keys(item.properties)).toEqual(["__title", "_id", "pathname"]);
    expect(item.properties.__title).toEqual({
      type: "string",
      nullable: true,
      title: "Título (opcional)",
      description: "Título do CMS.",
    });
    expect(item.properties._id).toMatchObject({
      type: "string",
      format: "dynamic-options",
      options: "site/loaders/admin/regulation.ts",
    });
    expect(item.required).toEqual(["pathname"]);
  }, 30_000);

  it("emits a hidden literal discriminator with const and an equal default", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/props.ts",
      `
        export interface Props {
          /** @hide true */
          __type: "image";
          src: string;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.__type).toEqual({
      type: "string",
      const: "image",
      default: "image",
      hide: "true",
      title: "__type",
    });
    // Hidden but defaulted: the admin writes the literal, so it stays required
    // (as in deco-cx/deco).
    expect(schema.required).toEqual(["__type", "src"]);
  }, 30_000);

  it("still leaves a hidden prop without a default out of `required`", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/props.ts",
      `
        export interface Props {
          /** @hide true */
          internal: string;
          src: string;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.internal.hide).toBe("true");
    expect(schema.required).toEqual(["src"]);
  }, 30_000);
});

describe("typeToJsonSchema with a recursive named type", () => {
  // A navigation tree written as `interface Link { submenu?: Link[] }`. The
  // cycle used to collapse to `{ type: "object" }`, so the admin edited the
  // submenu as an object instead of a list of links. deco-cx/deco emits the
  // type once as a definition and references it from inside the cycle.
  const source = `
    /** @title {{name}} */
    export interface Link {
      /** @title Name */
      name: string;
      /** @title Submenu */
      submenu?: Link[];
    }
    export interface Props { links: Link[] }
  `;
  const refId = `${Buffer.from("props.ts").toString("base64")}@Link`;

  it("references the type from inside the cycle and registers its definition", () => {
    const sf = strictProject().createSourceFile("/props.ts", source);
    const definitions: Record<string, any> = {};
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType(), new Set(), {
      definitions,
      rootDir: "/",
    });

    const item = schema.properties.links.items;
    expect(item.title).toBe("{{name}}");
    expect(item.properties.submenu).toEqual({
      type: "array",
      items: { $ref: `#/definitions/${refId}` },
      nullable: true,
      title: "Submenu",
    });

    // The definition the $ref points at is the full type, itself recursive.
    expect(Object.keys(definitions)).toEqual([refId]);
    expect(definitions[refId].title).toBe("{{name}}");
    expect(definitions[refId].required).toEqual(["name"]);
    expect(definitions[refId].properties.submenu.items).toEqual({
      $ref: `#/definitions/${refId}`,
    });
  }, 30_000);

  it("falls back to a bare object when there is no definitions sink", () => {
    const sf = strictProject().createSourceFile("/props.ts", source);
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.links.items.properties.submenu).toEqual({
      type: "object",
      nullable: true,
      title: "Submenu",
    });
  }, 30_000);
});

describe("typeToJsonSchema JSDoc tag parsing", () => {
  it("ignores `@description:` (colon after the tag name), as deco-cx/deco does", () => {
    const sf = strictProject().createSourceFile(
      "/props.ts",
      `
        export interface Props {
          /**
           * @title Título
           * @description: Nome que irá aparecer na pílula.
           */
          name: string;
          /** @description Kept. */
          path: string;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.name).toEqual({ type: "string", title: "Título" });
    expect(schema.properties.path.description).toBe("Kept.");
  }, 30_000);
});

describe("typeToJsonSchema Section-typed props", () => {
  // The framework's `Section` is opaque (`export type Section = any`), so a
  // Section-typed prop is a "pick any section" reference emitted as a
  // __SECTION_REF__ picker. This must keep working.
  it("emits a __SECTION_REF__ picker for the framework's opaque Section[]", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true },
    });
    const sf = project.createSourceFile(
      "props.ts",
      `
        type Section = any;
        export interface Props {
          children?: Section[] | null;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());

    expect(schema.properties.children).toMatchObject({
      type: "array",
      items: { $ref: "#/definitions/__SECTION_REF__" },
    });
  }, 30_000);

  // Regression (a production footer): a component that declares its own local
  // `type Section = { label; items }` used to collide with the magic name and
  // collapse into a non-editable __SECTION_REF__ picker — the footer columns
  // showed only a drag handle, no expand arrow, no form. A concretely-shaped
  // local type is user data and must render as an inline editable object.
  it("keeps a user-defined local `type Section` as an inline editable object", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true },
    });
    const sf = project.createSourceFile(
      "props.ts",
      `
        interface Item { label: string; href: string; }
        type Section = { label: string; items: Item[] };
        export interface Props {
          sections?: Section[];
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());

    const sections = schema.properties.sections;
    // Editable array of objects — NOT a section-picker reference.
    expect(sections.type).toBe("array");
    expect(JSON.stringify(sections)).not.toContain("__SECTION_REF__");

    const item = sections.items;
    expect(item.type).toBe("object");
    expect(item.properties.label).toMatchObject({ type: "string" });
    expect(item.properties.items.type).toBe("array");
    expect(item.properties.items.items.type).toBe("object");
    expect(item.properties.items.items.properties.href).toMatchObject({ type: "string" });
  }, 30_000);
});

describe("typeToJsonSchema loader block-ref matching", () => {
  // Regression: a loader that returns an array whose element type has no
  // resolvable name (`VNode[]`, `string[]`, …) used to be bucketed under the
  // generic key "Array". Because an array type's OWN symbol name is also
  // "Array", EVERY array-of-objects section prop (`Collection[]`, `Tab[]`)
  // matched that bucket and collapsed into a block-ref picker — so the array
  // was no longer editable and its item fields (label, nested loaders) all
  // disappeared from the CMS form. The two guards (drop the "Array" bucket at
  // registration; never look it up from an array prop's symbol name) keep the
  // array inline and editable.
  it("does not collapse an array-of-objects prop into a block-ref via the generic 'Array' bucket", () => {
    const project = new Project({
      useInMemoryFileSystem: true,
      compilerOptions: { skipLibCheck: true },
    });
    const sf = project.createSourceFile(
      "props.ts",
      `
        interface Product { productID: string; name: string; }
        interface Collection { label: string; products: Product[] | null; }
        export interface Props {
          collections: Collection[];
          topLevelProducts?: Product[] | null;
        }
      `,
    );
    const ctx = {
      // Mimics a site where List/Sections (VNode[]) and skuList (string[])
      // would otherwise land in an "Array" bucket, plus a real Product[] loader.
      outputTypeToLoaderKeys: new Map<string, string[]>([
        ["Product[]", ["site/loaders/algolia/products/list.ts"]],
        ["Array", ["site/loaders/List/Sections.tsx", "site/loaders/skuList.ts"]],
      ]),
    };

    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType(), new Set(), ctx);
    const collections = schema.properties.collections;

    // Stays an editable array of objects — NOT a block-ref anyOf.
    expect(collections.type).toBe("array");
    expect(collections.anyOf).toBeUndefined();

    const item = collections.items;
    expect(item.type).toBe("object");
    expect(item.properties.label).toMatchObject({ type: "string" });
    // The nested Product[] field still resolves to a loader picker (its type
    // name matches a registered loader output).
    expect(item.properties.products.anyOf).toEqual([
      { $ref: "#/definitions/Resolvable" },
      { $ref: "#/definitions/c2l0ZS9sb2FkZXJzL2FsZ29saWEvcHJvZHVjdHMvbGlzdC50cw==" },
    ]);

    // Control: a top-level Product[] prop still resolves to a loader picker.
    expect(schema.properties.topLevelProducts.anyOf).toEqual([
      { $ref: "#/definitions/Resolvable" },
      { $ref: "#/definitions/c2l0ZS9sb2FkZXJzL2FsZ29saWEvcHJvZHVjdHMvbGlzdC50cw==" },
    ]);
  }, 30_000);
});

// ---------------------------------------------------------------------------
// Default output path (.deco/) — subprocess, mirrors the pattern in
// generate-sections.test.ts. generate-schema.ts IS guarded by isMainModule(),
// but it's still driven as a subprocess here so the CLI's argv-parsed OUT_REL
// top-level code runs against a real cwd.
// ---------------------------------------------------------------------------

const SCRIPT = path.resolve(__dirname, "generate-schema.ts");

function runGenerator(
  args: string[],
  opts: { cwd?: string } = {},
): { stdout: string; stderr: string; code: number } {
  const r = cp.spawnSync("npx", ["tsx", SCRIPT, ...args], { encoding: "utf8", cwd: opts.cwd });
  return { stdout: r.stdout || "", stderr: r.stderr || "", code: r.status ?? 0 };
}

describe("generate-schema default output path (.deco/)", () => {
  let tmpDir: string;

  beforeEach(() => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "generate-schema-defaults-"));
    fs.writeFileSync(
      path.join(tmpDir, "tsconfig.json"),
      JSON.stringify({
        compilerOptions: {
          target: "ES2020",
          module: "ESNext",
          moduleResolution: "Bundler",
          jsx: "react-jsx",
          skipLibCheck: true,
          strict: true,
        },
      }),
    );
    const sectionsDir = path.join(tmpDir, "src", "sections");
    fs.mkdirSync(sectionsDir, { recursive: true });
    fs.writeFileSync(
      path.join(sectionsDir, "Hero.tsx"),
      [
        "export interface Props {",
        "  title: string;",
        "}",
        "export default function Hero(props: Props) { return null; }",
      ].join("\n"),
    );
  });

  afterEach(() => {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it("writes to .deco/meta.gen.json when no --out flag is passed", () => {
    const { code } = runGenerator(["--skip-apps"], { cwd: tmpDir });
    expect(code).toBe(0);

    const newDefault = path.join(tmpDir, ".deco", "meta.gen.json");
    expect(fs.existsSync(newDefault)).toBe(true);
    const meta = JSON.parse(fs.readFileSync(newDefault, "utf-8"));
    expect(meta.manifest.blocks.sections).toHaveProperty("site/sections/Hero.tsx");
  }, 30_000);

  it("emits deco.sectionPackages sections under their own namespace, with Props resolved across the package", () => {
    fs.writeFileSync(
      path.join(tmpDir, "package.json"),
      JSON.stringify({ deco: { sectionPackages: { ui: "@zeedog/ui" } } }),
    );
    const ui = path.join(tmpDir, "vendor", "ui");
    fs.mkdirSync(path.join(ui, "src", "sections"), { recursive: true });
    fs.mkdirSync(path.join(ui, "src", "components"), { recursive: true });
    fs.writeFileSync(path.join(ui, "package.json"), JSON.stringify({ name: "@zeedog/ui" }));
    fs.writeFileSync(
      path.join(ui, "src", "components", "Card.ts"),
      "export interface Card { image: string; }\n",
    );
    fs.writeFileSync(
      path.join(ui, "src", "sections", "Banner.tsx"),
      [
        'import type { Card } from "../components/Card";',
        "export interface Props { title: string; card: Card; }",
        "export default function Banner(props: Props) { return null; }",
      ].join("\n"),
    );
    fs.mkdirSync(path.join(tmpDir, "node_modules", "@zeedog"), { recursive: true });
    fs.symlinkSync(ui, path.join(tmpDir, "node_modules", "@zeedog", "ui"), "dir");

    const { code, stderr } = runGenerator(["--skip-apps"], { cwd: tmpDir });
    expect(code, stderr).toBe(0);

    const meta = JSON.parse(fs.readFileSync(path.join(tmpDir, ".deco", "meta.gen.json"), "utf-8"));
    expect(meta.manifest.blocks.sections).toHaveProperty("site/sections/Hero.tsx");
    expect(meta.manifest.blocks.sections["ui/sections/Banner.tsx"]).toMatchObject({
      namespace: "ui",
    });
    const section =
      meta.schema.definitions[Buffer.from("ui/sections/Banner.tsx").toString("base64")];
    const props = meta.schema.definitions[section.allOf[0].$ref.replace("#/definitions/", "")];
    expect(Object.keys(props.properties)).toEqual(["title", "card"]);
  }, 30_000);

  it("does not warn about a legacy default path", () => {
    const { code, stderr } = runGenerator(["--skip-apps"], { cwd: tmpDir });
    expect(code).toBe(0);
    expect(stderr).not.toContain("Generator default output moved");
  }, 30_000);
});

describe("typeToJsonSchema with RequestURLParam", () => {
  it("points a RequestURLParam prop at the requestToParam picker", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/props.ts",
      `
        type RequestURLParam = string;
        export interface Props {
          slug?: RequestURLParam;
          plain?: string;
        }
      `,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    const key = `${Buffer.from("website/functions/requestToParam.ts").toString("base64")}@RequestURLParam`;
    expect(schema.properties.slug).toEqual({ $ref: `#/definitions/${key}`, title: "Slug" });
    expect(schema.properties.plain.type).toBe("string");
  });
});

describe("default prop titles (deco-cx/deco beautify)", () => {
  it.each([
    ["marginTop", "Margin Top"],
    ["hideUnavailableItems", "Hide Unavailable Items"],
    ["title", "Title"],
    // Acronyms stay whole (deco-cx/deco split them letter by letter).
    ["CTA", "CTA"],
    ["titleCTA", "Title CTA"],
    ["taxID", "Tax ID"],
    ["jsonLDs", "Json L Ds"], // a plural acronym is ambiguous; same as upstream
    ["XMLHttpRequest", "XML Http Request"],
    ["RangePriceProps", "Range Price Props"],
  ])("%s → %s", (name, title) => {
    expect(beautify(name)).toBe(title);
  });

  it("titles an un-annotated prop, keeps an explicit @title", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/titles.ts",
      `export interface Props {
         marginTop?: number;
         /** @title Custom */
         noFlex?: boolean;
       }`,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    expect(schema.properties.marginTop.title).toBe("Margin Top");
    expect(schema.properties.noFlex.title).toBe("Custom");
  });
});

describe("widget detection by the whole type name", () => {
  it("does not treat a type that merely contains a widget name as that widget", () => {
    const project = strictProject();
    const sf = project.createSourceFile(
      "/colors.ts",
      `type Color = string;
       type ButtonColor = "Default" | "Primary";
       export interface Props {
         brand?: Color;
         buttons?: ButtonColor;
         variation?: "Simple" | "Color reverse";
       }`,
    );
    const schema = typeToJsonSchema(sf.getInterfaceOrThrow("Props").getType());
    applyWidgetFormat(schema.properties.brand, "Color");
    applyWidgetFormat(schema.properties.buttons, "ButtonColor");
    applyWidgetFormat(schema.properties.variation, '"Simple" | "Color reverse"');
    expect(schema.properties.variation.format).toBeUndefined();
    expect(schema.properties.brand.format).toBe("color-input");
    expect(schema.properties.buttons.format).toBeUndefined();
    expect(schema.properties.buttons.enum).toEqual(["Default", "Primary"]);
  });
});
