/*
 * tools-info.ts
 *
 * Copyright (C) 2022 Posit Software, PBC
 */

import { expandPath, safeExistsSync } from "../../core/path.ts";
import { join } from "../../deno_ral/path.ts";
import { getenv } from "../../core/env.ts";

import { existsSync } from "../../deno_ral/fs.ts";
import { os as platformOs } from "../../deno_ral/platform.ts";

export function hasTinyTex(): boolean {
  const binDir = tinyTexBinDir();
  if (!binDir) {
    return false;  // No bin directory found
  }

  // Check for tlmgr binary (critical package manager)
  const tlmgrBinary = platformOs === "windows" ? "tlmgr.bat" : "tlmgr";
  const tlmgrPath = join(binDir, tlmgrBinary);
  return safeExistsSync(tlmgrPath);
}

export function tinyTexInstallDir(): string | undefined {
  switch (platformOs) {
    case "windows": {
      let appDir = getenv("APPDATA", undefined);
      // use ProgramData if APPDATA is not set or contains spaces or non-ASCII characters
      if (!appDir || !appDir.match(/^[!-~]+$/)) {
        appDir = getenv("ProgramData", undefined);
      }
      return expandPath(join(appDir, "TinyTeX"));
    }
    case "linux":
      return expandPath("~/.TinyTeX");
    case "darwin":
      return expandPath("~/Library/TinyTeX");
    default:
      return undefined;
  }
}

export function tinyTexBinDir(): string | undefined {
  const basePath = tinyTexInstallDir();
  if (basePath) {
    switch (platformOs) {
      case "windows": {
        // TeX Live 2023 use windows now. Previous version were using win32
        const winPath = join(basePath, "bin\\win32\\");
        if (safeExistsSync(winPath)) return winPath;
        return join(basePath, "bin\\windows\\");
      }
      case "linux": {
        const linuxPath = join(basePath, `bin/${Deno.build.arch}-linux`);
        if (safeExistsSync(linuxPath)) return linuxPath;
        return undefined;
      }
      case "darwin": {
        const darwinPath = join(basePath, "bin/universal-darwin");
        if (safeExistsSync(darwinPath)) return darwinPath;
        return undefined;
      }
      default:
        return undefined;
    }
  } else {
    return undefined;
  }
}
