import { existsSync, readFileSync, writeFileSync } from "fs";

import { CommentArray, parse, stringify } from "comment-json";

import { bold, cyan } from "./picocolors";

export function setupTypeScript(envPath: string) {
  try {
    const ts = require("typescript");
    if (!ts) {
      return;
    }

    const configFileName = ts.findConfigFile(
      "./",
      ts.sys.fileExists,
      "tsconfig.json",
    );

    const userConfig = parse(
      readFileSync(configFileName, {
        encoding: "utf-8",
      }),
    );

    if (
      typeof userConfig !== "object" ||
      !userConfig ||
      Array.isArray(userConfig)
    ) {
      return;
    }

    const output: string[] = [];
    let updatedConfig = false;

    if (!existsSync(envPath)) {
      writeFileSync(
        envPath,
        `/// <reference types="nativewind/types" />

// NOTE: This file should not be edited and should be committed with your source code. It is generated by NativeWind.`,
      );
      output.push(`Created ${cyan(envPath)}`);
    }

    userConfig.include ??= new CommentArray(envPath);
    if (
      Array.isArray(userConfig.include) &&
      !userConfig.include.includes(envPath)
    ) {
      userConfig.include.push(envPath);
      updatedConfig = true;
      output.push(
        `Updated ${configFileName} to include the ${cyan(envPath)} file`,
      );
    }

    if (updatedConfig) {
      writeFileSync(configFileName, stringify(userConfig, null, 2));
    }

    if (output.length) {
      console.log(
        `${cyan(bold("NativeWind"))} made the following changes to your project to support TypeScript:\n  - ${output.join("\n  - ")}`,
      );
    }
  } catch {}
}
