import "server-only";

import { cache } from "react";

import { countRedirects } from "@/features/redirects/queries";
import {
  bool,
  cmsData,
  cmsPaths,
  field,
  idOf,
  isoOrNull,
  list,
  num,
  str,
  strOrNull,
  withFallback,
} from "@/lib/cms/api";
import type { ContentStatus } from "@/lib/cms/types";
import { htmlToText } from "@/lib/sanitize";

import { analyzeSeo, seoScore, type SeoCheck } from "./analysis";

/** Below this, or with any failing check, an article needs attention. */
export const SEO_HEALTHY_SCORE = 80;

export type SeoHealthFilter = "attention" | "healthy";

/** An article's SEO health as sent to Client Components. */
export type SeoHealthRow = {
  id: string;
  title: string;
  slug: string;
  status: ContentStatus;
  focusKeyword: string | null;
  updatedAt: string;
  score: number;
  checks: SeoCheck[];
  /** Failures first, then warnings. */
  issues: SeoCheck[];
  needsAttention: boolean;
  robotsIndex: boolean;
};

/** The fields of a `blog_posts` row (from `GET admin/blogs`) the analysis reads. */
type SeoBlog = {
  id: string;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  status: ContentStatus;
  updatedAt: string;
  seoTitle: string | null;
  metaDescription: string | null;
  focusKeyword: string | null;
  featuredImage: string | null;
  featuredImageAlt: string | null;
  robotsIndex: boolean;
  canonicalUrl: string | null;
};

function toSeoBlog(row: unknown): SeoBlog {
  const status = str(row, "status");
  return {
    id: idOf(row),
    title: str(row, "title"),
    slug: str(row, "slug"),
    excerpt: str(row, "excerpt"),
    content: str(row, "content"),
    status: status === "PUBLISHED" || status === "SCHEDULED" ? status : "DRAFT",
    updatedAt: isoOrNull(row, "updated_at") ?? new Date(0).toISOString(),
    seoTitle: strOrNull(row, "seo_title"),
    metaDescription: strOrNull(row, "meta_description"),
    focusKeyword: strOrNull(row, "focus_keyword"),
    featuredImage: strOrNull(row, "featured_image"),
    featuredImageAlt: strOrNull(row, "featured_image_alt"),
    robotsIndex: bool(row, "robots_index", true),
    canonicalUrl: strOrNull(row, "canonical_url"),
  };
}

/** Pages of 100 read per request; 2,000 articles is far beyond today's blog. */
const PAGE_SIZE = 100;
const MAX_PAGES = 20;

/** Every article from the CMS, page by page (the list rows carry content and SEO fields). */
async function fetchAllArticles() {
  const rows: unknown[] = [];
  for (let page = 1; page <= MAX_PAGES; page++) {
    const data = await cmsData<unknown>(cmsPaths.blogs, {
      query: { page, pageSize: PAGE_SIZE, sort: "updated" },
    });
    const batch = Array.isArray(data) ? data : list(data, "data");
    rows.push(...batch);
    const lastPage = num(data, "last_page", page);
    if (Array.isArray(data) || batch.length === 0 || page >= lastPage) break;
    if (page === MAX_PAGES && field(data, "next_page_url")) {
      console.warn(
        `[seo] analyzed the first ${MAX_PAGES * PAGE_SIZE} articles only`,
      );
    }
  }
  return rows
    .map(toSeoBlog)
    .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
}

const ISSUE_ORDER: Record<SeoCheck["status"], number> = {
  fail: 0,
  warn: 1,
  pass: 2,
};

function toHealthRow(blog: SeoBlog): SeoHealthRow {
  const checks = analyzeSeo({
    title: blog.title,
    slug: blog.slug,
    excerpt: blog.excerpt,
    wordCount: htmlToText(blog.content).split(/\s+/).filter(Boolean).length,
    seoTitle: blog.seoTitle,
    metaDescription: blog.metaDescription,
    focusKeyword: blog.focusKeyword,
    featuredImage: blog.featuredImage,
    featuredImageAlt: blog.featuredImageAlt,
    robotsIndex: blog.robotsIndex,
    canonicalUrl: blog.canonicalUrl,
  });
  const score = seoScore(checks);
  const issues = checks
    .filter((check) => check.status !== "pass")
    .sort((a, b) => ISSUE_ORDER[a.status] - ISSUE_ORDER[b.status]);

  return {
    id: blog.id,
    title: blog.title,
    slug: blog.slug,
    status: blog.status,
    focusKeyword: blog.focusKeyword,
    updatedAt: blog.updatedAt,
    score,
    checks,
    issues,
    needsAttention:
      score < SEO_HEALTHY_SCORE ||
      issues.some((issue) => issue.status === "fail"),
    robotsIndex: blog.robotsIndex,
  };
}

/**
 * Every article, analyzed, newest change first. Word counts need the full
 * content, so this reads it once per request and the summary and table share it.
 */
const analyzeAllArticles = cache(async () =>
  (await fetchAllArticles()).map(toHealthRow),
);

/**
 * Numbers for the summary cards. Health figures cover published articles only.
 * `redirects` is null while the CMS has no redirects endpoint.
 */
export async function getSeoSummary() {
  const [rows, redirects] = await Promise.all([
    analyzeAllArticles(),
    withFallback<number | null>(countRedirects(), null),
  ]);
  const published = rows.filter((row) => row.status === "PUBLISHED");
  return {
    totalArticles: rows.length,
    published: published.length,
    needsAttention: published.filter((row) => row.needsAttention).length,
    hiddenFromSearch: published.filter((row) => !row.robotsIndex).length,
    redirects,
  };
}

export async function listSeoHealth({
  status,
  health,
  query,
  page = 1,
  pageSize = 20,
}: {
  status?: ContentStatus;
  health?: SeoHealthFilter;
  query?: string;
  page?: number;
  pageSize?: number;
}) {
  const q = query?.trim().toLowerCase();
  const rows = (await analyzeAllArticles()).filter(
    (row) =>
      (!status || row.status === status) &&
      (!health || row.needsAttention === (health === "attention")) &&
      (!q ||
        row.title.toLowerCase().includes(q) ||
        row.slug.toLowerCase().includes(q)),
  );

  return {
    items: rows.slice((page - 1) * pageSize, page * pageSize),
    total: rows.length,
    page,
    pageSize,
  };
}
