//! Top-level entry emission: `index.js` + `index.d.ts` that re-export
//! every collection's `<name>.json`.
//!
//! Two `.d.ts` modes:
//! - **Velite-style** (config is `.ts`/`.js`/`.mjs`): re-import the user's
//!   config, infer record types via `typeof import(..)['collections']`.
//! - **Self-contained** (TOML / no config): per-collection TS interface
//!   from `schema = { ... }`, else the generic `DocRecord` shape.

use std::path::Path;

use dmc_diagnostic::{Code, DiagResult};
use duck_diagnostic::diag;

use crate::engine::collection::Collection;
use crate::engine::schema_ts::schema_to_ts_object;

use crate::engine::utils::{pascal_case, relative_from};

/// Pick the right `.d.ts` mode and write `index.js` + `index.d.ts`.
pub fn write_index(out_dir: &Path, collections: &[Collection], format: &str, config_path: Option<&Path>) -> DiagResult {
  let names: Vec<&str> = collections.iter().map(|c| c.name.as_str()).collect();
  write_index_js(out_dir, &names, format)?;

  let ts_cfg =
    config_path.filter(|p| matches!(p.extension().and_then(|s| s.to_str()), Some("ts") | Some("js") | Some("mjs"),));

  match ts_cfg {
    Some(p) => {
      let rel = relative_from(out_dir, p);
      write_dts_velite_style(out_dir, &names, &rel)?;
    },
    None => write_dts_self_contained(out_dir, collections)?,
  }
  Ok(())
}

fn write_index_js(out_dir: &Path, names: &[&str], format: &str) -> DiagResult {
  let mut js = String::from("// This file is generated by dmc. DO NOT EDIT.\n\n");
  if format == "cjs" {
    for name in names {
      js.push_str(&format!("exports.{name} = require('./{name}.json')\n"));
    }
  } else {
    for name in names {
      js.push_str(&format!("export {{ default as {name} }} from './{name}.json' with {{ type: 'json' }}\n",));
    }
  }
  let path = out_dir.join("index.js");
  std::fs::write(&path, js).map_err(|e| diag!(Code::IoWrite, format!("write {}: {}", path.display(), e)))
}

fn write_dts_self_contained(out_dir: &Path, collections: &[Collection]) -> DiagResult {
  let mut dts = String::from(
    "// This file is generated by dmc. DO NOT EDIT.

export interface TocItem { title: string; url: string; items: TocItem[] }
export interface Metadata { readingTime: number; wordCount: number }
export interface BaseCollection {
  body: string
  content: string
  excerpt: string
  metadata: Metadata
  toc: TocItem[]
  contentType: string
  flattenedPath: string
  permalink: string
  slug: string
  sourceFileDir: string
  sourceFileName: string
  sourceFilePath: string
  html?: string
}
export interface DocCollection extends BaseCollection { [frontmatterField: string]: unknown }

",
  );

  for c in collections {
    let iface = pascal_case(&c.name) + "Collection";
    match &c.schema {
      Some(schema) => {
        dts.push_str(&format!("export interface {iface} extends BaseCollection "));
        dts.push_str(&schema_to_ts_object(schema));
        dts.push('\n');
        dts.push_str(&format!("export declare const {}: {iface}[]\n\n", c.name));
      },
      None => {
        dts.push_str(&format!("export declare const {}: DocCollection[]\n\n", c.name));
      },
    }
  }

  let path = out_dir.join("index.d.ts");
  std::fs::write(&path, dts).map_err(|e| diag!(Code::IoWrite, format!("write {}: {}", path.display(), e)))
}

fn write_dts_velite_style(out_dir: &Path, names: &[&str], cfg_rel: &str) -> DiagResult {
  let mut dts = String::from("// This file is generated by dmc. DO NOT EDIT.\n\n");
  dts.push_str(&format!("import type __dmc from '{cfg_rel}'\n\n"));
  dts.push_str("type Collections = typeof __dmc['collections']\n");
  dts.push_str("type CollectionName = keyof Collections\n");
  dts.push_str("type RecordOf<K extends CollectionName> =\n");
  dts.push_str("  Collections[K] extends { schema: { _output: infer T } } ? T : unknown\n\n");
  for name in names {
    dts.push_str(&format!("export declare const {name}: RecordOf<'{name}'>[]\n"));
  }
  let path = out_dir.join("index.d.ts");
  std::fs::write(&path, dts).map_err(|e| diag!(Code::IoWrite, format!("write {}: {}", path.display(), e)))
}
