import { QuartzConfig } from "../cfg"
import { ProcessedContent, QuartzPluginData } from "../plugins/vfile"
import { FileTrieNode } from "./fileTrie"
import { FilePath, FullSlug } from "./path"

export interface Argv {
  directory: string
  verbose: boolean
  output: string
  serve: boolean
  watch: boolean
  port: number
  wsPort: number
  remoteDevHost?: string
  concurrency?: number
}

export type BuildTimeTrieData = QuartzPluginData & {
  slug: string
  title: string
  filePath: string
}

/**
 * Mapping from logical asset names (e.g. "index.css") to their content-hashed
 * filenames (e.g. "index-a3f2c1b.css"). Populated by the ComponentResources
 * emitter before pages are rendered.
 */
export type HashedResourceNames = Record<string, string>

export interface BuildCtx {
  buildId: string
  argv: Argv
  cfg: QuartzConfig
  allSlugs: FullSlug[]
  allFiles: FilePath[]
  trie?: FileTrieNode<BuildTimeTrieData>
  incremental: boolean
  /** Virtual pages generated by page type plugins (e.g. tag pages, folder pages, bases pages) */
  virtualPages: ProcessedContent[]
  /** Content-hashed asset filenames, populated by ComponentResources emitter */
  hashedResourceNames?: HashedResourceNames
  /** Maps CSS content strings to their emitted hashed filenames. Populated by ComponentResources. */
  componentCssMap?: Map<string, string>
  /** Maps inline CSS/JS content to extracted external file paths. Populated by ComponentResources. */
  extractedInlineResources?: Map<string, string>
}

export function trieFromAllFiles(allFiles: QuartzPluginData[]): FileTrieNode<BuildTimeTrieData> {
  const trie = new FileTrieNode<BuildTimeTrieData>([])
  allFiles.forEach((file) => {
    if (file.frontmatter) {
      trie.add({
        ...file,
        slug: file.slug!,
        title: file.frontmatter.title,
        filePath: file.filePath!,
      })
    }
  })

  return trie
}

export type WorkerSerializableBuildCtx = Omit<BuildCtx, "cfg" | "trie">
