/**
 * nexus-agents/research - Research Index Markdown Generation
 *
 * Functions for generating markdown sections of RESEARCH_INDEX.md.
 *
 * @see research-index-generator.ts - Main generator
 * @see Issue #367 - Deterministic RESEARCH_INDEX.md generation
 */

import { getTimeProvider } from '../core/index.js';
import { TOPIC_DESCRIPTIONS, RESEARCH_TOPICS } from './research-schemas.js';
import type { PaperWithId, TechniqueWithId, RegistryStats } from './research-index-types.js';
import { capitalizeKebab as capitalizeTopicName } from '../utils/text-utils.js';

// Re-export for backward compatibility
export { capitalizeTopicName };

// ============================================================================
// Date Utilities
// ============================================================================

/**
 * Get current date in ET timezone (YYYY-MM-DD format).
 */
export function getETDate(): string {
  const now = new Date(getTimeProvider().now());
  const formatter = new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/New_York',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  });
  const parts = formatter.formatToParts(now);
  const y = parts.find((p) => p.type === 'year')?.value ?? '';
  const m = parts.find((p) => p.type === 'month')?.value ?? '';
  const d = parts.find((p) => p.type === 'day')?.value ?? '';
  return `${y}-${m}-${d}`;
}

// ============================================================================
// Section Generators - Header
// ============================================================================

/**
 * Generate frontmatter with checksums for drift detection.
 */
export function generateFrontmatter(papersChecksum: string, techniquesChecksum: string): string {
  const dateStr = getETDate();
  return `<!--
  AUTO-GENERATED FILE - DO NOT EDIT MANUALLY
  Generated by: nexus-agents research index --generate
  Last generated: ${dateStr} (ET)
  Source checksums:
    papers: sha256:${papersChecksum}
    techniques: sha256:${techniquesChecksum}
-->

`;
}

/**
 * Generate header section with title and stats summary.
 */
export function generateHeader(stats: RegistryStats, dateStr: string): string {
  return `# Nexus-Agents Research Index

**Generated:** ${dateStr} (ET)
**Total Papers:** ${String(stats.totalPapers)} | **Techniques:** ${String(stats.totalTechniques)} | **Topics:** ${String(stats.totalTopics)}

---`;
}

/**
 * Generate quick stats section with technique status breakdown.
 */
export function generateQuickStats(stats: RegistryStats): string {
  const { techniquesByStatus } = stats;
  return `## Quick Stats

| Status      | Papers | Techniques |
| ----------- | ------ | ---------- |
| Implemented | -      | ${String(techniquesByStatus['implemented'])}         |
| In Progress | -      | ${String(techniquesByStatus['in-progress'])}          |
| Planned     | -      | ${String(techniquesByStatus['planned'])}          |
| Not Started | -      | ${String(techniquesByStatus['not-started'])}          |
| Rejected    | -      | ${String(techniquesByStatus['rejected'])}          |

> **Note:** Paper-level status tracking deprecated. Technique status is source of truth.

---`;
}

// ============================================================================
// Section Generators - Topics
// ============================================================================

/**
 * Generate topics table section with paper/technique counts.
 */
export function generateTopicsTable(stats: RegistryStats): string {
  const rows = stats.topicStats.map((ts) => {
    const topicDisplay = capitalizeTopicName(ts.topic);
    const topicLink = `[${topicDisplay}](topics/${ts.topic}/README.md)`;
    const desc = TOPIC_DESCRIPTIONS[ts.topic];
    return `| ${topicLink} | ${String(ts.papers)} | ${String(ts.techniques)} | ${desc ?? ''} |`;
  });

  return `## Topics

| Topic | Papers | Techniques | Description |
| ----- | ------ | ---------- | ----------- |
${rows.join('\n')}

---`;
}

// ============================================================================
// Section Generators - Techniques
// ============================================================================

/**
 * Generate a single technique row for priority tables.
 */
function generateTechniqueRow(t: TechniqueWithId): string {
  const name = `[${t.name}](registry/techniques.yaml#${t.id})`;
  const topic = t.topic;
  const metricsArr = Object.entries(t.metrics);
  const metrics = metricsArr.length > 0 ? metricsArr.map(([k, v]) => `${k}: ${v}`).join(', ') : '-';
  const issue = t.implementation_issue !== null ? `#${String(t.implementation_issue)}` : '-';
  return `| ${name} | ${topic} | ${metrics} | ${issue} |`;
}

/**
 * Generate P1 techniques section (high-impact, architecture-aligned).
 */
export function generateP1Section(techniques: readonly TechniqueWithId[]): string {
  const p1 = techniques.filter((t) => t.priority === 'P1');
  if (p1.length === 0) return '';

  const rows = p1.map(generateTechniqueRow);
  return `## Priority 1 (P1) Techniques

These techniques are high-impact and align well with the current architecture.

| Technique | Topic | Key Metrics | Issue |
| --------- | ----- | ----------- | ----- |
${rows.join('\n')}

---`;
}

/**
 * Generate P2 techniques section (medium-impact).
 */
export function generateP2Section(techniques: readonly TechniqueWithId[]): string {
  const p2 = techniques.filter((t) => t.priority === 'P2');
  if (p2.length === 0) return '';

  const rows = p2.map(generateTechniqueRow);
  return `## Priority 2 (P2) Techniques

Medium-impact or requiring moderate changes.

| Technique | Topic | Key Metrics | Issue |
| --------- | ----- | ----------- | ----- |
${rows.join('\n')}

---`;
}

// ============================================================================
// Section Generators - Papers
// ============================================================================

/**
 * Generate recently reviewed papers section.
 */
export function generateRecentPapers(papers: readonly PaperWithId[], limit: number): string {
  const withDates = papers
    .filter(
      (p): p is PaperWithId & { reviewed_date: string } => typeof p.reviewed_date === 'string'
    )
    .sort((a, b) => b.reviewed_date.localeCompare(a.reviewed_date))
    .slice(0, limit);

  if (withDates.length === 0) return '';

  const rows = withDates.map((p) => {
    const escapedTitle = p.title.replace(/\|/g, '-');
    const title =
      typeof p.url === 'string' && p.url.length > 0 ? `[${escapedTitle}](${p.url})` : escapedTitle;
    const topic = p.topics[0] ?? '-';
    return `| ${p.reviewed_date} | ${title} | ${topic} | - |`;
  });

  return `## Recently Reviewed Papers

| Date | Paper | Topic | Priority |
| ---- | ----- | ----- | -------- |
${rows.join('\n')}

---`;
}

/**
 * Generate papers by topic section.
 */
export function generatePapersByTopic(papers: readonly PaperWithId[]): string {
  const sections: string[] = [];

  for (const topic of RESEARCH_TOPICS) {
    if (topic === 'cli-tools') continue; // Skip if typically empty

    const topicPapers = papers.filter((p) => p.topics.includes(topic));
    if (topicPapers.length === 0) continue;

    const topicDisplay = capitalizeTopicName(topic);
    const list = topicPapers
      .map((p) => {
        const title =
          typeof p.url === 'string' && p.url.length > 0 ? `[${p.title}](${p.url})` : p.title;
        const summary = p.summary?.split('\n')[0]?.trim() ?? '';
        return summary.length > 0 ? `- ${title} - ${summary}` : `- ${title}`;
      })
      .join('\n');

    sections.push(`### ${topicDisplay} (${String(topicPapers.length)} papers)\n\n${list}`);
  }

  if (sections.length === 0) return '';

  return `## Papers by Topic

${sections.join('\n\n')}

---`;
}

// ============================================================================
// Section Generators - GitHub & Tags
// ============================================================================

/**
 * Generate GitHub issues section linking techniques to tracking issues.
 */
export function generateGitHubIssues(techniques: readonly TechniqueWithId[]): string {
  const withIssues = techniques.filter((t) => t.implementation_issue !== null);
  if (withIssues.length === 0) return '';

  const rows = withIssues.map((t) => {
    const papers = t.source_papers.length > 0 ? t.source_papers.join(', ') : '-';
    return `| #${String(t.implementation_issue ?? 0)} | ${t.name} | ${papers} |`;
  });

  return `## GitHub Issues

| Issue | Feature | Related Papers |
| ----- | ------- | -------------- |
${rows.join('\n')}

---`;
}

/**
 * Generate search tags section for discoverability.
 */
export function generateSearchTags(techniques: readonly TechniqueWithId[]): string {
  const allTags = new Set<string>();
  for (const t of techniques) {
    for (const tag of t.tags) {
      allTags.add(tag);
    }
  }

  const tagList = Array.from(allTags)
    .sort()
    .slice(0, 20)
    .map((tag) => `\`#${tag}\``)
    .join(' ');

  return `## Search Tags

${tagList}

---`;
}

// ============================================================================
// Section Generators - Footer
// ============================================================================

/**
 * Generate registry files section with links.
 */
export function generateRegistryFiles(stats: RegistryStats): string {
  return `## Registry Files

- [papers.yaml](registry/papers.yaml) - All ${String(stats.totalPapers)} papers with metadata
- [techniques.yaml](registry/techniques.yaml) - All ${String(stats.totalTechniques)} techniques with status
- [sources.yaml](registry/sources.yaml) - Product docs and other sources

---`;
}

/**
 * Generate how to contribute section.
 */
export function generateContributing(dateStr: string): string {
  return `## How to Contribute

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on adding new research.

---

_Generated from YAML registries. Last updated: ${dateStr} (ET)_
`;
}
