import util from "node:util";
import { exec as _exec } from "child_process";
import { Logger, LogLevel, createDefaultLogger } from "./logger";
import {z} from "zod";

export const exec = util.promisify(_exec);
export { Logger, LogLevel, createDefaultLogger };

export function toKebabCase(anyCaseName: string) {
  const spacesRemoved = anyCaseName.replace(/\s/g, "-");
  const lettersOnly = spacesRemoved.replace(/[^0-9a-zA-Z\-]/g, "");
  const lowerCased = lettersOnly.toLowerCase();
  return lowerCased;
}

export function logReplacer(key: string, value: any) {
  if (key === "data" && typeof value === "string" && value.length > 20) {
    return value.slice(0, 20) + "...[truncated]";
  }
  return value;
}

// If you change this, also change the type for apptile_context in baseAgent.ts
export const apptileContextZodSchema = z.object({
  app_id: z.string(),
  plugin_root: z.string().describe("Root folder of the current plugin"),
  plugins_dir: z.string().describe("Path of the plugins directory in remoteCode"),
  supabase_creds: z.object({
    SUPABASE_ACCESS_TOKEN: z.string(),
    SUPABASE_REFRESH_TOKEN: z.string(),
    ACCESS_TOKEN_EXPIRES_IN: z.number(),
    SUPABASE_PROJECT_REF: z.string(),
    SUPABASE_ANON_KEY: z.string().optional(),
    APPTILE_SUPABASE_CLIENT_ID: z.string().optional(),
    APPTILE_SUPABASE_CLIENT_SECRET: z.string().optional()
  }).nullable()
}).nullable().describe("This should always be passed as null by the LLM. It will be set to the correct path by the tool.")

export function createTargetName(anyCaseName: string, appId: string) {
  const kebab = toKebabCase(anyCaseName);
  const targetName = `${appId}_${kebab}`;
  return targetName;
}

export function toCamelCase(kebabCaseName: string) {
  const words = kebabCaseName.split("-");
  for (let i = 1; i < words.length; ++i) {
    words[i] = words[i][0].toUpperCase() + words[i].slice(1);
  }
  return words.join("");
}

export default {
  comment:
    "This is only exported beacuse otherwise node does not recognize this file as a module",
};

export function makeHeadersWithCookie(
  cookie: string | null,
  extraHeaders: Record<string, string>
) {
  //Check if this is working in production environment
  const header = {
    Accept: "application/json, text/plain, */*",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    Connection: "keep-alive",
    "If-None-Match": 'W/"5b1-kyqqkRyAnA0NO0WgKmBhdQQi7Qo"',
    Origin: "https://app.apptile.io",
    Referer: "https://app.apptile.io",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "cross-site",
    "User-Agent":
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "sec-ch-ua":
      '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    ...extraHeaders,
  };
  if (process.env.NODE_ENV === "production") {
    console.log("This is a production environment");
    return {
      headers: header,
    };
  } else {
    console.log("This is a development environment");
    if (!cookie) {
      throw new Error("Cookie not provided");
    }
    return {
      headers: {
        ...header,
        Cookie: cookie,
      },
    };
  }
}

export const getMidUrlIntegrationsValue = () => {
  return process.env.NODE_ENV === "production" ? "admin/api/apps" : "api/apps";
};

export const getMidUrlAppValue = () => {
  return process.env.NODE_ENV === 'production'? 'admin/api/v2/apps' : 'api/v2/app';
}