import { createRequire } from 'module'; const require = createRequire(import.meta.url);
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });

// src/index.ts
import { execFile } from "child_process";
import { existsSync, mkdirSync } from "fs";
import { dirname, join as join2 } from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";

// src/constants.ts
var TL_VERSION = "0.24.8";
var RELEASES_BASE = `https://github.com/teal-language/tl/releases/download/v${TL_VERSION}`;
var PLATFORM_MAP = {
  "linux-x64": {
    asset: `tl-${TL_VERSION}-linux-x86_64.tar.gz`,
    exe: "tl"
  },
  "win32-x64": {
    asset: `tl-${TL_VERSION}-windows-x86_64.zip`,
    exe: "tl.exe"
  }
};

// src/tlconfig.ts
import { execFileSync } from "child_process";
import { unlinkSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
function readTlConfig(cwd) {
  const tl = getTlBinary();
  const luaSnippet = `
        local cfg = dofile("tlconfig.lua")
        local parts = {}
        if cfg.source_dir then parts[#parts+1] = '"source_dir":"' .. cfg.source_dir .. '"' end
        if cfg.build_dir  then parts[#parts+1] = '"build_dir":"'  .. cfg.build_dir  .. '"' end
        if cfg.files then
        local fs = {}
        for _, f in ipairs(cfg.files) do fs[#fs+1] = '"' .. f .. '"' end
        parts[#parts+1] = '"files":[' .. table.concat(fs, ",") .. "]"
        end
        print("{" .. table.concat(parts, ",") .. "}")
    `;
  const tmpFile = join(tmpdir(), `teal-cfx-config-${process.pid}.lua`);
  try {
    writeFileSync(tmpFile, luaSnippet, "utf8");
    const output = execFileSync(tl, [
      "run",
      tmpFile
    ], {
      cwd,
      encoding: "utf8"
    }).trim();
    return JSON.parse(output);
  } catch {
    throw new Error(`[@tlfx/compiler] Failed to parse tlconfig.lua in ${cwd}.
  Make sure the file exists and is valid Lua.`);
  } finally {
    try {
      unlinkSync(tmpFile);
    } catch {
    }
  }
}
__name(readTlConfig, "readTlConfig");

// src/index.ts
var execFileAsync = promisify(execFile);
var __dirname = dirname(fileURLToPath(import.meta.url));
function getTlBinary() {
  if (process.env.TL_BINARY) return process.env.TL_BINARY;
  const platformKey = `${process.platform}-${process.arch}`;
  const platformInfo = PLATFORM_MAP[platformKey];
  if (!platformInfo) {
    throw new Error(`[@tlfx/compiler] No bundled tl binary for ${platformKey}. Set TL_BINARY=/path/to/tl in your environment.`);
  }
  const bundled = join2(__dirname, "..", "bin", platformInfo.exe);
  if (!existsSync(bundled)) {
    throw new Error(`[@tlfx/compiler] Binary not found at ${bundled}. Try reinstalling the package or set TL_BINARY=/path/to/tl.`);
  }
  return bundled;
}
__name(getTlBinary, "getTlBinary");
async function check(filePath) {
  const tl = getTlBinary();
  try {
    const { stdout, stderr } = await execFileAsync(tl, [
      "check",
      filePath
    ]);
    return {
      ok: true,
      output: stdout + stderr
    };
  } catch (err) {
    const e = err;
    return {
      ok: false,
      output: (e.stdout ?? "") + (e.stderr ?? "")
    };
  }
}
__name(check, "check");
async function compile(filePath, options = {}) {
  const tl = getTlBinary();
  const outFile = options.outFile ?? filePath.replace(/\.tl$/, ".lua");
  if (options.outFile) {
    mkdirSync(dirname(options.outFile), {
      recursive: true
    });
  }
  try {
    const { stdout, stderr } = await execFileAsync(tl, [
      "gen",
      filePath,
      "-o",
      outFile
    ]);
    return {
      ok: true,
      output: stdout + stderr,
      outFile
    };
  } catch (err) {
    const e = err;
    return {
      ok: false,
      output: (e.stdout ?? "") + (e.stderr ?? "")
    };
  }
}
__name(compile, "compile");
async function build(cwd = process.cwd()) {
  const config = readTlConfig(cwd);
  const sourceDir = config.source_dir ?? ".";
  const buildDir = config.build_dir ?? ".";
  const files = config.files ?? [];
  if (files.length === 0) {
    return {
      ok: false,
      output: "[@tlfx/compiler] No files listed in tlconfig.lua.\n"
    };
  }
  const results = await Promise.all(files.map((file) => {
    const inFile = join2(cwd, sourceDir, file);
    const outFile = join2(cwd, buildDir, file.replace(/\.tl$/, ".lua"));
    return compile(inFile, {
      outFile
    });
  }));
  const allOutput = results.map((r) => r.output).join("");
  const allOk = results.every((r) => r.ok);
  if (allOk) {
    const compiled = results.map((r) => `  \u2192 ${r.outFile}`).join("\n");
    return {
      ok: true,
      output: `${allOutput}
[@tlfx/compiler] Built ${files.length} file(s):
${compiled}
`
    };
  }
  return {
    ok: false,
    output: allOutput
  };
}
__name(build, "build");
export {
  build,
  check,
  compile,
  getTlBinary
};
