export const COMMAND_NAMES = ["seed", "constraints", "table-registry", "help"] as const;
export type CommandName = (typeof COMMAND_NAMES)[number];

export type CommandArgs = {
  command: CommandName;
  sql: string;
  cql: string;
  includeConstraints: boolean;
  ifNotExistTable: boolean;
  supabaseUrl?: string;
  supabaseKey?: string;
  supabaseConfigPath?: string;
  dbConfigOutput?: string;
  registrySchemaPath?: string;
  registryPath?: string;
  showHelp: boolean;
};

const normalizeCommand = (input?: string): CommandName | undefined => {
  if (!input) {
    return undefined;
  }
  const normalized = input.trim().toLowerCase();
  if (normalized === "table-registry" || normalized === "registry") {
    return "table-registry";
  }
  if (COMMAND_NAMES.includes(normalized as CommandName)) {
    return normalized as CommandName;
  }
  return undefined;
};

export const parseArgs = (): CommandArgs => {
  const args: CommandArgs = {
    command: "seed",
    sql: "seed.sql",
    cql: "seed.cql",
    includeConstraints: false,
    ifNotExistTable: false,
    showHelp: false,
  };

  for (const raw of process.argv.slice(2)) {
    if (raw === "--help" || raw === "-h") {
      args.command = "help";
      args.showHelp = true;
      continue;
    }
    if (raw.startsWith("--command=")) {
      const value = normalizeCommand(raw.split("=", 2)[1]);
      if (value) {
        args.command = value;
      }
      continue;
    }
    if (raw === "--generate-table-registry") {
      args.command = "table-registry";
      continue;
    }
    if (raw.startsWith("--sql=")) {
      args.sql = raw.split("=", 2)[1] || args.sql;
      continue;
    }
    if (raw.startsWith("--cql=")) {
      args.cql = raw.split("=", 2)[1] || args.cql;
      continue;
    }
    if (raw === "--include-constraints-sql") {
      args.includeConstraints = true;
      continue;
    }
    if (raw === "--if-not-exist-table") {
      args.ifNotExistTable = true;
      continue;
    }
    if (raw.startsWith("--supabase-url=")) {
      args.supabaseUrl = raw.split("=", 2)[1];
      continue;
    }
    if (raw.startsWith("--supabase-key=")) {
      args.supabaseKey = raw.split("=", 2)[1];
      continue;
    }
    if (raw.startsWith("--supabase-config=")) {
      args.supabaseConfigPath = raw.split("=", 2)[1];
      continue;
    }
    if (raw.startsWith("--db-config-output=")) {
      args.dbConfigOutput = raw.split("=", 2)[1];
      continue;
    }
    if (raw.startsWith("--registry-schema-path=")) {
      args.registrySchemaPath = raw.split("=", 2)[1];
      continue;
    }
    if (raw.startsWith("--registry-path=")) {
      args.registryPath = raw.split("=", 2)[1];
      continue;
    }
  }

  return args;
};
