import fs from "fs/promises";
import path from "path";

import { russAuthor } from "@/content/blog/authors";
import type { Post } from "@/content/blog/posts";
import { tagsToCategories } from "@/lib/atproto-feed";

interface Frontmatter {
  title?: string;
  description?: string;
  publishDate?: string;
  ogImage?: string;
  tags?: string[];
  atUri?: string;
}

function unquote(value: string): string {
  const trimmed = value.trim();
  if (
    (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
    (trimmed.startsWith("'") && trimmed.endsWith("'"))
  ) {
    return trimmed.slice(1, -1);
  }
  return trimmed;
}

function parseFrontmatter(
  raw: string
): { data: Frontmatter; body: string } | null {
  const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
  if (!match) return null;

  const [, yaml, body] = match;
  const data: Frontmatter = {};
  const lines = yaml.split(/\r?\n/);

  let currentListKey: keyof Frontmatter | null = null;

  for (const line of lines) {
    if (!line.trim()) continue;

    const listItem = line.match(/^\s+-\s+(.*)$/);
    if (listItem && currentListKey) {
      const arr = (data[currentListKey] ?? []) as string[];
      arr.push(unquote(listItem[1]));
      (data[currentListKey] as unknown) = arr;
      continue;
    }

    const kv = line.match(/^([a-zA-Z][a-zA-Z0-9_]*):\s*(.*)$/);
    if (!kv) {
      currentListKey = null;
      continue;
    }

    const [, key, rawValue] = kv;
    const value = rawValue.trim();

    if (value === "") {
      currentListKey = key as keyof Frontmatter;
      if (!(key in data)) (data as Record<string, unknown>)[key] = [];
      continue;
    }

    currentListKey = null;
    (data as Record<string, string>)[key] = unquote(value);
  }

  return { data, body };
}

export async function loadLocalDraft(slug: string): Promise<Post | undefined> {
  if (process.env.NODE_ENV === "production") return undefined;

  const filePath = path.join(process.cwd(), "src/content/blog", `${slug}.md`);
  let raw: string;
  try {
    raw = await fs.readFile(filePath, "utf-8");
  } catch {
    return undefined;
  }

  const parsed = parseFrontmatter(raw);
  if (!parsed) return undefined;

  const { data, body } = parsed;
  const { title } = data;
  if (!title) return undefined;

  const datetime = data.publishDate ? new Date(data.publishDate) : new Date();

  return {
    id: `draft-${slug}`,
    title,
    href: `/blog/${slug}`,
    description: data.description ?? "",
    datetime,
    categories: tagsToCategories(data.tags ?? []),
    author: russAuthor,
    body,
    atUri: data.atUri || undefined,
  };
}
