import { defineEventHandler } from 'h3';
import { generateData } from './data.mjs';
import 'pathe';
import 'node:fs';
import 'unenv/runtime/npm/debug';
import 'chalk';
import 'c12';
import 'untyped';
import 'pg';
import 'node:crypto';
import 'mkdirp';
import 'camelcase';
import 'pascalcase';
import 'pluralize';

const defaultCardinality = formatCardinality("0+--0+"), defaultRelationship = "associates with";
function parseColumnComment(comment) {
  const splitChar = "|";
  const lines = comment.split(new RegExp(`(?<!\\\\)[${splitChar}]`)).map((line) => line.replace(/\\\|/g, "|"));
  const links = parseLink(lines);
  if (links.succeeded) {
    lines.splice(lines.indexOf(links.linkLine), 1);
    if (links.cardinalityLine)
      lines.splice(lines.indexOf(links.cardinalityLine), 1);
    if (links.relationshipLine)
      lines.splice(lines.indexOf(links.relationshipLine), 1);
  }
  const extraColumns = parseExtraColumns(lines);
  if (extraColumns.succeeded)
    for (const originalLine of extraColumns.originalLines)
      lines.splice(lines.indexOf(originalLine), 1);
  return {
    link: links.succeeded ? links.link : void 0,
    cardinality: links.succeeded ? links.cardinality : void 0,
    relationship: links.succeeded ? links.relationship : void 0,
    extraColumns: extraColumns.succeeded ? extraColumns.extraColumns : void 0,
    description: lines.filter(Boolean).join(splitChar)
  };
}
function parseLink(lines) {
  const linkLine = lines.find((line) => line.startsWith("link:") || line.startsWith("link="));
  if (!linkLine)
    return { succeeded: false };
  let cardinalityLine = lines.find((line) => line.startsWith("cardinality:") || line.startsWith("cardinality=")), cardinality = defaultCardinality;
  if (cardinalityLine) {
    const parsedCardinality = cardinalityLine.replace(/^cardinality[:=]/, "");
    if (parsedCardinality.match(/^(0\+|1|1\+|01)(--|\.\.)(0\+|1|1\+|01)$/))
      cardinality = formatCardinality(parsedCardinality);
    else
      cardinalityLine = void 0;
  }
  const relationshipLine = lines.find((line) => line.startsWith("relationship:") || line.startsWith("relationship=")), relationship = (relationshipLine == null ? void 0 : relationshipLine.replace(/^relationship[:=]/, "")) || defaultRelationship;
  return {
    succeeded: true,
    link: linkLine.replace(/^link[:=]/, ""),
    cardinality,
    linkLine,
    cardinalityLine,
    relationship,
    relationshipLine
  };
}
function parseExtraColumns(lines) {
  const extraColumns = {};
  const originalLines = [];
  for (const line of lines) {
    const match = line.match(/^(?<key>[^:]+):(?<value>.+)/) || line.match(/^(?<key>[^=]+)=(?<value>.+)/);
    if (!match)
      continue;
    let { key, value } = match.groups;
    if (!key || !value)
      continue;
    try {
      value = JSON.parse(value);
    } catch {
    }
    extraColumns[key.replace(/^\[|\]$/g, "")] = value;
    originalLines.push(line);
  }
  if (Object.keys(extraColumns).length === 0)
    return { succeeded: false };
  return {
    succeeded: true,
    extraColumns,
    originalLines
  };
}
function formatCardinality(string) {
  const leftReplacements = {
    "0+": "}o",
    "1": "||",
    "1+": "}|",
    "01": "|o"
  }, rightReplacements = {
    "0+": "o{",
    "1": "||",
    "1+": "|{",
    "01": "o|"
  };
  const [left, right] = string.split(/--|\.\./), splitter = string.includes("--") ? "--" : "..";
  return `${leftReplacements[left]}${splitter}${rightReplacements[right]}`;
}

const table = defineEventHandler(async () => {
  const data = await generateData();
  return data.map((database) => {
    const schemas = [...new Set(database.tables.map((table) => table.schema_id))];
    return {
      database_name: database.database,
      database_url: database.hostPort,
      schemas: schemas.map((schema) => {
        var _a;
        const tables = database.tables.filter((table) => table.schema_id === schema);
        return {
          schema_name: (_a = tables[0]) == null ? void 0 : _a.schema_name,
          tables: tables.map((table) => {
            var _a2;
            return {
              table_name: table.table_name,
              columns: (((_a2 = database.classes.find((c) => c.class_id === table.table_id)) == null ? void 0 : _a2.attributes) || []).map((attr) => {
                if (!attr.comment)
                  return {
                    column_name: attr.attribute_name,
                    data_type: attr.type_name,
                    column_default: attr.default,
                    is_nullable: !attr.not_null,
                    comment: ""
                  };
                const parsedComment = parseColumnComment(attr.comment);
                return {
                  column_name: attr.attribute_name,
                  data_type: attr.type_name,
                  column_default: attr.default,
                  is_nullable: !attr.not_null,
                  comment: parsedComment.description,
                  ...parsedComment.extraColumns || {}
                };
              })
            };
          })
        };
      })
    };
  });
});

export { table as default };
//# sourceMappingURL=table.mjs.map
