import type { Metadata } from 'next';
import { getRuns, getRejections, getCandidates } from '@/lib/api';
import { Section, EmptyState } from '@/components/sections/Section';

export const metadata: Metadata = {
  title: 'Pipeline status',
  description: 'Ingestion and editorial pipeline status for AI Radar.',
  // An internal build view has no business in search results.
  robots: { index: false, follow: false },
};

/**
 * Internal build view: what the pipeline did on its last run.
 *
 * Kept deliberately plain — it is an instrument, not a page anyone is
 * meant to enjoy. The reject breakdown is the useful part: it is the
 * only way to tell whether the filter is dropping things it should keep.
 */
export default async function StatusPage() {
  // Locale-independent: this is an internal instrument, English only.
  const [runs, rejections, candidates] = await Promise.all([
    getRuns(),
    getRejections(),
    getCandidates(),
  ]);

  const latest = runs[0];

  return (
    <main id="main" className="page" style={{ paddingBlock: 'var(--s10)' }}>
      <header className="prose">
        <p className="t-meta">INTERNAL</p>
        <h1 className="t-h1" style={{ marginTop: 'var(--s3)' }}>
          Pipeline status
        </h1>
      </header>

      {!latest ? (
        <Section title="Last run">
          <EmptyState
            title="No ingestion run recorded yet."
            body="Start the API and POST to /api/pipeline/ingest to fetch from the seeded sources."
          />
        </Section>
      ) : (
        <Section title="Last ingestion run">
          <p className="counts">
            <span>
              Sources <b>{latest.sources_checked}</b>
            </span>
            <span>
              Fetched <b>{latest.fetched.toLocaleString()}</b>
            </span>
            <span>
              Kept <b>{latest.prefilter_kept}</b>
            </span>
            <span>
              Rejected free{' '}
              <b>
                {latest.fetched > 0
                  ? `${(((latest.fetched - latest.prefilter_kept) / latest.fetched) * 100).toFixed(1)}%`
                  : '0%'}
              </b>
            </span>
          </p>
          <p className="t-body-sm prose" style={{ marginTop: 'var(--s4)', color: 'var(--text-2)' }}>
            Filtering is deterministic code, so everything rejected here cost nothing.
          </p>
        </Section>
      )}

      {rejections.length > 0 && (
        <Section title="Why items were rejected">
          <ul className="row-list">
            {rejections.map((r) => (
              <li key={r.reject_reason} className="story-row">
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    padding: 'var(--s3) 0',
                    gap: 'var(--s4)',
                  }}
                >
                  <span className="t-row" style={{ textTransform: 'capitalize' }}>
                    {r.reject_reason.replace(/_/g, ' ')}
                  </span>
                  <span className="t-meta" style={{ fontVariantNumeric: 'tabular-nums' }}>
                    {Number(r.count).toLocaleString()}
                  </span>
                </div>
              </li>
            ))}
          </ul>
        </Section>
      )}

      {candidates.length > 0 && (
        <Section title="Candidates awaiting the editor">
          <ul className="row-list">
            {candidates.map((c) => (
              <li key={c.id} className="story-row">
                <a
                  href={c.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{ display: 'block', padding: 'var(--s3) 0' }}
                >
                  <span className="t-row">{c.title}</span>
                  <span className="t-meta" style={{ display: 'block', marginTop: 'var(--s1)' }}>
                    {c.source_name}
                  </span>
                </a>
              </li>
            ))}
          </ul>
        </Section>
      )}
    </main>
  );
}
