// Pre-chisel rewrite of user-library bare-specifier imports. chisel's resolver hard-errors on any
// bare import (the whole SDK is globals), so a project that imports a component library by its slug
// —`import { Card } from "acme-ui"`— is rewritten here to the injected library tree under
// `/__lib/<slug>/…` BEFORE chisel runs. Only libraries present in the dependency map are known
// slugs; any other bare specifier is an author error, surfaced with a friendly message instead of
// chisel's generic one. Static string-literal specifiers only — dynamic `import()` is unsupported
// (documented). Chisel itself is untouched. See docs/library-system-plan.md §4.

/** Cheap pre-check so the regexes don't run over files with no imports at all. */
export const hasImportStatement = (src: string): boolean => src.includes("import") || src.includes("from")

// A static `from "…"` clause (import-from OR export-from). Anchored at a statement boundary
// (line start / `;` / `}`) and disallowing quotes/backticks/semicolons between the keyword and
// `from`, so it can never span into a string literal or a neighbouring statement. Named-import
// lists may span multiple lines (newlines are allowed between the keyword and `from`).
const IMPORT_FROM_RE = /(^|[;\n}])(\s*(?:import|export)\b[^"'`;]*?\bfrom\s*)(["'])([^"'\n]+)\3/g

// A side-effect `import "…"` (a bare quote directly after the keyword — not `import x`, not `import(`).
const SIDE_EFFECT_RE = /(^|[;\n}])(\s*import\s*)(["'])([^"'\n]+)\3/g

const isRelativeOrAbsolute = (spec: string): boolean =>
  spec.startsWith("/") || spec.startsWith("./") || spec.startsWith("../")

/**
 * Rewrite every known-library bare import in `src` to its `/__lib/<slug>/…` path. Relative and
 * absolute specifiers pass through untouched; an unknown bare specifier throws a friendly Error.
 * `slugs` is the set of library slugs available to this project (its dependency map's keys).
 */
export const rewriteLibraryImports = (src: string, slugs: Set<string>): string => {
  const rewriteSpec = (spec: string): string => {
    if (isRelativeOrAbsolute(spec)) return spec
    const slash = spec.indexOf("/")
    const slug = slash === -1 ? spec : spec.slice(0, slash)
    if (slugs.has(slug)) {
      // `acme-ui` → `/__lib/acme-ui/index`; `acme-ui/theme` → `/__lib/acme-ui/theme`.
      const sub = slash === -1 ? "/index" : spec.slice(slash)
      return `/__lib/${slug}${sub}`
    }
    // Legacy worker-module imports (`import { UIScreen } from "ui"`) predate the globals-only SDK —
    // chisel would reject them anyway; say so here instead of "Unknown library".
    if (slug === "ui" || slug === "creator" || slug === "utils") {
      throw new Error(`import from "${slug}": the SDK needs no imports — UIScreen, Scene, etc. are globals; remove this import line.`)
    }
    throw new Error(`Unknown library "${slug}" — add it in Settings → Libraries, or use a relative path like "./${slug}".`)
  }

  let out = src.replace(IMPORT_FROM_RE, (_m, boundary, head, quote, spec) =>
    `${boundary}${head}${quote}${rewriteSpec(spec)}${quote}`)
  out = out.replace(SIDE_EFFECT_RE, (m, boundary, head, quote, spec) =>
    isRelativeOrAbsolute(spec) ? m : `${boundary}${head}${quote}${rewriteSpec(spec)}${quote}`)
  return out
}
