// Copyright 2026 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

///|
pub struct WgslImportTarget {
  raw_path : String
  alias_name : String
} derive(Eq, Debug)

///|
pub struct WgslResolvedImportModule {
  module_path : String
  rel_path : String
} derive(Eq, Debug)

///|
fn join_wgsl_import_prefix(prefix : String, path : String) -> String {
  let lhs = prefix.trim().to_owned()
  let rhs = path.trim().to_owned()
  if lhs == "" {
    rhs
  } else if rhs == "" {
    lhs
  } else {
    "\{lhs}::\{rhs}"
  }
}

///|
pub fn collect_wgsl_import_targets(
  spec : String,
  prefix : String,
  targets : Array[WgslImportTarget],
) -> Unit {
  parse_wgsl_import_targets(trim_trailing_semicolons(spec), prefix, targets) catch {
    _ => ()
  }
}

///|
pub fn normalize_shader_rel_path(rel : String) -> String {
  let mut text = rel.trim().to_owned()
  let n = text.length()
  let mut i = 0
  while i < n && text.code_unit_at(i).to_int() == 47 { // '/'
    i = i + 1
  }
  if i != 0 {
    text = text[i:n].to_owned()
  }
  while text.has_prefix("./") {
    text = text[2:text.length()].to_owned()
  }
  if text.has_prefix("assets/") {
    text = text[7:text.length()].to_owned()
  }
  let normalized_segments : Array[String] = []
  for raw_segment in text.split("/") {
    let segment = raw_segment.to_owned().trim().to_owned()
    if segment == "" || segment == "." {
      continue
    }
    if segment == ".." {
      if normalized_segments.length() > 0 {
        normalized_segments.pop() |> ignore
      }
      continue
    }
    normalized_segments.push(segment)
  }
  normalized_segments.join("/")
}

///|
fn shader_parent_rel_path(rel_path : String) -> String {
  let normalized = normalize_shader_rel_path(rel_path)
  if normalized == "" {
    return ""
  }
  let segments : Array[String] = []
  for raw_segment in normalized.split("/") {
    let segment = raw_segment.to_owned()
    if segment != "" {
      segments.push(segment)
    }
  }
  if segments.length() == 0 {
    return ""
  }
  segments.pop() |> ignore
  segments.join("/")
}

///|
fn unquote_wgsl_import_path(import_path : String) -> String? {
  let trimmed = import_path.trim().to_owned()
  if trimmed.length() >= 2 &&
    trimmed.code_unit_at(0).to_int() == 34 &&
    trimmed.code_unit_at(trimmed.length() - 1).to_int() == 34 {
    return Some(trimmed[1:trimmed.length() - 1].to_owned())
  }
  None
}

///|
fn wgsl_import_looks_like_file_path(import_path : String) -> Bool {
  if unquote_wgsl_import_path(import_path) is Some(_) {
    return true
  }
  let trimmed = import_path.trim().to_owned()
  if trimmed == "" {
    return false
  }
  trimmed.contains("/") ||
  trimmed.has_suffix(".wgsl") ||
  trimmed.has_prefix("./") ||
  trimmed.has_prefix("../")
}

///|
pub fn resolve_wgsl_import_file_path(
  importer_rel_path : String,
  import_path : String,
) -> String? {
  resolve_wgsl_import_file_path_from_registry(
    registered_wgsl_source_registry_singleton, importer_rel_path, import_path,
  )
}

///|
fn resolve_wgsl_import_file_path_from_registry(
  registry : WgslSourceRegistry,
  importer_rel_path : String,
  import_path : String,
) -> String? {
  guard wgsl_import_looks_like_file_path(import_path) else { return None }
  let raw_path = match unquote_wgsl_import_path(import_path) {
    Some(path) => path
    None => import_path.trim().to_owned()
  }
  let normalized = if raw_path.has_prefix("./") || raw_path.has_prefix("../") {
    let parent = shader_parent_rel_path(importer_rel_path)
    if parent == "" {
      normalize_shader_rel_path(raw_path)
    } else {
      normalize_shader_rel_path("\{parent}/\{raw_path}")
    }
  } else {
    normalize_shader_rel_path(raw_path)
  }
  if normalized == "" {
    return None
  }
  if registry.registered_source(normalized) is Some(_) {
    return Some(normalized)
  }
  None
}

///|
pub fn resolve_wgsl_source_file_path(
  _assets_base : String,
  rel : String,
) -> String? {
  let normalized_rel = normalize_shader_rel_path(rel)
  if normalized_rel == "" {
    return None
  }
  if registered_wgsl_source_registry_singleton.registered_source(normalized_rel)
    is Some(_) {
    return Some(normalized_rel)
  }
  None
}

///|
fn normalize_wgsl_scan_path(path : String) -> String {
  let trimmed = path.trim().to_owned()
  if trimmed == "" {
    return ""
  }
  let parts : Array[String] = []
  let mut start = 0
  for i in 0.. String {
  let lhs = normalize_wgsl_scan_path(prefix)
  let rhs = normalize_wgsl_scan_path(path)
  if lhs == "" {
    return rhs
  }
  if rhs == "" {
    return lhs
  }
  "\{lhs}/\{rhs}"
}

///|
fn normalize_wgsl_scan_prefix(prefix : String) -> String {
  normalize_shader_rel_path(normalize_wgsl_scan_path(prefix))
}

///|
fn normalize_wgsl_scan_extensions(extensions : Array[String]) -> Array[String] {
  let normalized : Array[String] = []
  for extension in extensions {
    let trimmed = extension.trim().to_owned()
    if trimmed == "" {
      continue
    }
    if trimmed.has_prefix(".") {
      normalized.push(trimmed)
    } else {
      normalized.push(".\{trimmed}")
    }
  }
  normalized
}

///|
fn wgsl_scan_path_is_excluded(
  rel_path : String,
  exclude_prefixes : Array[String],
) -> Bool {
  let normalized_rel_path = normalize_shader_rel_path(rel_path)
  for prefix in exclude_prefixes {
    let normalized_prefix = normalize_wgsl_scan_prefix(prefix)
    if normalized_prefix == "" {
      continue
    }
    if normalized_rel_path == normalized_prefix ||
      normalized_rel_path.has_prefix("\{normalized_prefix}/") {
      return true
    }
  }
  false
}

///|
fn wgsl_scan_path_matches_extension(
  rel_path : String,
  extensions : Array[String],
) -> Bool {
  if extensions.length() == 0 {
    return true
  }
  for extension in extensions {
    if rel_path.has_suffix(extension) {
      return true
    }
  }
  false
}

///|
fn collect_scanned_wgsl_source_files(
  fs_path : String,
  rel_prefix : String,
  options : WgslSourceScanOptions,
  normalized_extensions : Array[String],
  out : Array[WgslSourceFile],
) -> Unit raise @fs.IOError {
  let entries = @fs.read_dir(fs_path)
  entries.sort()
  for entry_name in entries {
    let entry_rel_path = if rel_prefix == "" {
      normalize_wgsl_scan_path(entry_name)
    } else {
      join_wgsl_scan_path(rel_prefix, entry_name)
    }
    if wgsl_scan_path_is_excluded(entry_rel_path, options.exclude_prefixes) {
      continue
    }
    let entry_fs_path = join_wgsl_scan_path(fs_path, entry_name)
    if @fs.is_dir(entry_fs_path) {
      if options.recursive {
        collect_scanned_wgsl_source_files(
          entry_fs_path, entry_rel_path, options, normalized_extensions, out,
        )
      }
      continue
    }
    if !@fs.is_file(entry_fs_path) {
      continue
    }
    if !wgsl_scan_path_matches_extension(
        normalize_shader_rel_path(entry_rel_path),
        normalized_extensions,
      ) {
      continue
    }
    out.push(WgslSourceFile::{
      rel_path: normalize_shader_rel_path(entry_rel_path),
      source: @fs.read_file_to_string(entry_fs_path),
    })
  }
}

///|
pub fn scan_wgsl_source_files(
  root : String,
  options : WgslSourceScanOptions,
) -> Array[WgslSourceFile] raise @fs.IOError {
  let normalized_root = normalize_wgsl_scan_path(root)
  let scan_root = if normalized_root == "" { "." } else { normalized_root }
  let files : Array[WgslSourceFile] = []
  collect_scanned_wgsl_source_files(
    scan_root,
    "",
    options,
    normalize_wgsl_scan_extensions(options.extensions),
    files,
  )
  files
}

///|
pub fn scan_wgsl_source_files_checked(
  root : String,
  options : WgslSourceScanOptions,
) -> (Array[WgslSourceFile], Array[WgslDiagnostic]) raise @fs.IOError {
  let files = scan_wgsl_source_files(root, options)
  (files, analyze_wgsl_source_files_for_registry(files))
}

///|
let registered_wgsl_source_registry_singleton : WgslSourceRegistry = WgslSourceRegistry::default()

///|
fn copy_wgsl_source_registry_map(
  source_registry : @hashmap.HashMap[String, String],
) -> @hashmap.HashMap[String, String] {
  let copied : @hashmap.HashMap[String, String] = @hashmap.HashMap::new()
  for entry in source_registry.iter() {
    let (rel_path, source) = entry
    copied.set(rel_path, source)
  }
  copied
}

///|
fn copy_wgsl_import_module_map(
  module_paths : @hashmap.HashMap[String, String],
) -> @hashmap.HashMap[String, String] {
  let copied : @hashmap.HashMap[String, String] = @hashmap.HashMap::new()
  for entry in module_paths.iter() {
    let (module_path, rel_path) = entry
    copied.set(module_path, rel_path)
  }
  copied
}

///|
fn clear_wgsl_source_registry(
  source_registry : @hashmap.HashMap[String, String],
  module_paths : @hashmap.HashMap[String, String],
) -> Unit {
  source_registry.clear()
  module_paths.clear()
}

///|
fn register_wgsl_source_into(
  source_registry : @hashmap.HashMap[String, String],
  module_paths : @hashmap.HashMap[String, String],
  rel_path : String,
  source : String,
  explicit_module_path : String?,
) -> String? {
  let normalized_rel = normalize_shader_rel_path(rel_path)
  if normalized_rel == "" {
    return None
  }
  source_registry.set(normalized_rel, source)
  let mut module_path : String? = explicit_module_path
  if module_path is None {
    let (detected_import_path, _, _) = get_preprocessor_data(source)
    module_path = detected_import_path
  }
  if module_path is Some(path) && path != "" {
    module_paths.set(path, normalized_rel)
  }
  Some(normalized_rel)
}

///|
pub fn clear_registered_wgsl_source_registry() -> Unit {
  registered_wgsl_source_registry_singleton.clear()
}

///|
pub fn register_wgsl_source(rel_path : String, source : String) -> Unit {
  ignore(
    registered_wgsl_source_registry_singleton.register_source(
      rel_path,
      source,
      None,
    ),
  )
}

///|
fn push_wgsl_registry_diagnostic(
  diagnostics : Array[WgslDiagnostic],
  severity : WgslDiagnosticSeverity,
  message : String,
  rel_path : String?,
  symbol_name : String?,
) -> Unit {
  diagnostics.push(WgslDiagnostic::{
    severity,
    message,
    rel_path,
    symbol_name,
    generated_start: None,
    source_start: None,
  })
}

///|
fn wgsl_diagnostics_has_error(diagnostics : Array[WgslDiagnostic]) -> Bool {
  for diagnostic in diagnostics {
    if diagnostic.severity == WgslDiagnosticSeverity::Error {
      return true
    }
  }
  false
}

///|
pub fn analyze_wgsl_source_files_for_registry(
  files : Array[WgslSourceFile],
) -> Array[WgslDiagnostic] {
  registered_wgsl_source_registry_singleton.analyze_source_files(files)
}

///|
fn analyze_wgsl_source_files_for_registry_against(
  existing_rel_to_source : @hashmap.HashMap[String, String],
  existing_modules : @hashmap.HashMap[String, String],
  files : Array[WgslSourceFile],
  diagnostics : Array[WgslDiagnostic],
) -> Unit {
  let batch_rel_to_source : @hashmap.HashMap[String, String] = @hashmap.HashMap::new()
  let batch_module_to_rel : @hashmap.HashMap[String, String] = @hashmap.HashMap::new()

  for source_file in files {
    let normalized_rel = normalize_shader_rel_path(source_file.rel_path)
    if normalized_rel == "" {
      push_wgsl_registry_diagnostic(
        diagnostics,
        WgslDiagnosticSeverity::Error,
        "registry source file path resolves to an empty normalized path",
        Some(source_file.rel_path),
        None,
      )
      continue
    }

    if batch_rel_to_source.get(normalized_rel) is Some(existing_source) {
      if existing_source != source_file.source {
        push_wgsl_registry_diagnostic(
          diagnostics,
          WgslDiagnosticSeverity::Error,
          "multiple WGSL source files normalize to the same rel_path with different contents",
          Some(normalized_rel),
          None,
        )
      }
    } else if existing_rel_to_source.get(normalized_rel)
      is Some(existing_source) {
      if existing_source != source_file.source {
        push_wgsl_registry_diagnostic(
          diagnostics,
          WgslDiagnosticSeverity::Error,
          "bulk registry would overwrite an existing rel_path with different contents",
          Some(normalized_rel),
          None,
        )
      }
    }
    batch_rel_to_source.set(normalized_rel, source_file.source)

    let (import_path, _, _) = get_preprocessor_data(source_file.source)
    guard import_path is Some(module_path) && module_path != "" else {
      continue
    }

    if batch_module_to_rel.get(module_path) is Some(existing_rel) {
      if existing_rel != normalized_rel {
        push_wgsl_registry_diagnostic(
          diagnostics,
          WgslDiagnosticSeverity::Error,
          "multiple WGSL source files define the same #define_import_path in one batch",
          Some(normalized_rel),
          Some(module_path),
        )
      }
    } else if existing_modules.get(module_path) is Some(existing_rel) {
      if existing_rel != normalized_rel {
        push_wgsl_registry_diagnostic(
          diagnostics,
          WgslDiagnosticSeverity::Error,
          "bulk registry would overwrite an existing #define_import_path with a different rel_path",
          Some(normalized_rel),
          Some(module_path),
        )
      }
    }
    batch_module_to_rel.set(module_path, normalized_rel)
  }
}

///|
pub fn register_wgsl_source_files_checked(
  files : Array[WgslSourceFile],
) -> Array[WgslDiagnostic] {
  let diagnostics : Array[WgslDiagnostic] = []
  registered_wgsl_source_registry_singleton.register_source_files_checked(
    files, diagnostics,
  )
  diagnostics
}

///|
fn register_wgsl_source_files_checked_into(
  source_registry : @hashmap.HashMap[String, String],
  module_paths : @hashmap.HashMap[String, String],
  files : Array[WgslSourceFile],
  diagnostics : Array[WgslDiagnostic],
) -> Unit {
  let existing_rel_to_source = copy_wgsl_source_registry_map(source_registry)
  let existing_modules = copy_wgsl_import_module_map(module_paths)
  analyze_wgsl_source_files_for_registry_against(
    existing_rel_to_source, existing_modules, files, diagnostics,
  )
  if wgsl_diagnostics_has_error(diagnostics) {
    return
  }
  register_wgsl_source_files_into(source_registry, module_paths, files)
}

///|
pub fn register_wgsl_source_files(files : Array[WgslSourceFile]) -> Unit {
  registered_wgsl_source_registry_singleton.register_source_files(files)
}

///|
fn register_wgsl_source_files_into(
  source_registry : @hashmap.HashMap[String, String],
  module_paths : @hashmap.HashMap[String, String],
  files : Array[WgslSourceFile],
) -> Unit {
  for file in files {
    ignore(
      register_wgsl_source_into(
        source_registry,
        module_paths,
        file.rel_path,
        file.source,
        None,
      ),
    )
  }
}

///|
pub fn registered_wgsl_source(rel_path : String) -> String? {
  registered_wgsl_source_registry_singleton.registered_source(rel_path)
}

///|
fn registered_wgsl_source_from_registry(
  source_registry : @hashmap.HashMap[String, String],
  rel_path : String,
) -> String? {
  let normalized_rel = normalize_shader_rel_path(rel_path)
  if normalized_rel == "" {
    return None
  }
  source_registry.get(normalized_rel)
}

///|
pub fn copy_registered_wgsl_source_files() -> Array[WgslSourceFile] {
  registered_wgsl_source_registry_singleton.copy_source_files()
}

///|
fn copy_wgsl_source_files_from_registry(
  source_registry : @hashmap.HashMap[String, String],
) -> Array[WgslSourceFile] {
  let files : Array[WgslSourceFile] = []
  for entry in source_registry.iter() {
    let (rel_path, source) = entry
    files.push(WgslSourceFile::{ rel_path, source })
  }
  files
}

///|
pub fn copy_registered_wgsl_import_module_paths() -> @hashmap.HashMap[
  String,
  String,
] {
  registered_wgsl_source_registry_singleton.copy_import_module_paths()
}

///|
fn wgsl_module_path_to_rel_path(module_path : String) -> String {
  let mut rel = "shaders/"
  let mut first = true
  for seg in module_path.split("::") {
    let text = seg.to_owned()
    if text == "" {
      continue
    }
    if first {
      first = false
    } else {
      rel = "\{rel}/"
    }
    rel = "\{rel}\{text}"
  }
  "\{rel}.wgsl"
}

///|
fn wgsl_module_path_to_rel_path_namespace(module_path : String) -> String {
  let segments : Array[String] = []
  for seg in module_path.split("::") {
    let text = seg.to_owned().trim().to_owned()
    if text != "" {
      segments.push(text)
    }
  }
  if segments.length() == 0 {
    return ""
  }
  let mut rel = "shaders/\{segments[0]}"
  for i in 1.. String {
  wgsl_module_path_to_rel_path_namespace(module_path)
}

///|
pub fn build_wgsl_import_module_paths(
  _assets_base : String,
) -> @hashmap.HashMap[String, String] {
  copy_registered_wgsl_import_module_paths()
}

///|
fn resolve_wgsl_import_module_in_registry(
  registry : WgslSourceRegistry,
  import_path : String,
  modules : @hashmap.HashMap[String, String],
) -> WgslResolvedImportModule? {
  let segments : Array[String] = []
  for seg in import_path.split("::") {
    let text = seg.to_owned().trim().to_owned()
    if text != "" {
      segments.push(text)
    }
  }
  while segments.length() > 0 {
    let mut module_path = segments[0]
    for i in 1.. ignore
  }
  None
}

///|
pub fn resolve_wgsl_import_module(
  _assets_base : String,
  import_path : String,
  modules : @hashmap.HashMap[String, String],
) -> WgslResolvedImportModule? {
  resolve_wgsl_import_module_in_registry(
    registered_wgsl_source_registry_singleton, import_path, modules,
  )
}