import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from './node_modules/.pnpm/@typescript_vfs@1.6.1_typescript@5.5.4/node_modules/@typescript/vfs/dist/vfs.esm.js';
import './node_modules/.pnpm/@valtown_codemirror-ts@3.0.0-9_@codemirror_autocomplete@6.17.0_@codemirror_language@6.10.2_@c_nk442kkgahslbcycc3bdhtpz6m/node_modules/@valtown/codemirror-ts/dist/worker.js';
import { expose } from './node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.js';
import * as ts from 'typescript';
import { setupTypeAcquisition } from './node_modules/.pnpm/@cxai_ata@0.0.0_typescript@5.5.4/node_modules/@cxai/ata/dist/index.js';
import { createWorker } from './node_modules/.pnpm/@valtown_codemirror-ts@3.0.0-9_@codemirror_autocomplete@6.17.0_@codemirror_language@6.10.2_@c_nk442kkgahslbcycc3bdhtpz6m/node_modules/@valtown/codemirror-ts/dist/worker/createWorker.js';

async function createTSEnv() {
  const fsMap = await createDefaultMapFromCDN(
    { target: ts.ScriptTarget.ES2022 },
    ts.version,
    false,
    ts
  );
  const system = createSystem(fsMap);
  const env = createVirtualTypeScriptEnvironment(system, [], ts, {
    lib: ["ES2022"]
  });
  const ata = setupTypeAcquisition({
    projectName: "CM ATA Project",
    typescript: ts,
    logger: console,
    fetcher: (input, init) => {
      console.log("fetcher", input, init);
      const url = typeof input === "string" ? input : "url" in input ? input.url : input.toString();
      const uri = new URL(url);
      console.log("fetcher", uri, input);
      switch (uri.protocol) {
        case "jsr:":
        case "npm:":
          uri.host = "esm.sh";
          uri.protocol = "https:";
          uri.searchParams.set("target", uri.searchParams.get("target") ?? "deno");
          break;
        case "deno:":
          uri.host = "deno.land";
          uri.protocol = "https:";
      }
      return fetch(uri.toString(), init);
    },
    delegate: {
      receivedFile: (code, path) => {
        env.createFile(path, code);
      },
      started: () => {
        console.log("ATA start");
      },
      progress: (downloaded, total) => {
        console.log(`Got ${downloaded} out of ${total}`);
      },
      finished: (vfs) => {
        console.log("ATA done", vfs);
      }
    }
  });
  return {
    env,
    onFileUpdated(_env, _path, code) {
      ata(code);
    }
  };
}
const worker = createWorker(createTSEnv());
expose(worker);
