import { promises as fs } from 'fs';
import path from 'path';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Card, CardContent } from '@/components/ui/card';

async function getMarkdownContent() {
  // process.cwd() is the root of the Next.js project (the 'frontend' directory)
  const root = path.join(process.cwd(), '..', 'docs');
  const candidates = [
    path.join(root, '1_requirements', '20251109_[Active]_user-guide.md'),
    path.join(root, '1_requirements', '20251108_[Active]_requirements.md'),
    path.join(root, '2_architecture', '20251116_[Active]_system_architecture.md'),
  ];
  for (const p of candidates) {
    try {
      const content = await fs.readFile(p, 'utf8');
      return content;
    } catch {
      // try next
    }
  }
  return [
    '# 文档加载失败',
    '',
    '未找到以下任意文档：',
    '- docs/1_requirements/20251109_[Active]_user-guide.md',
    '- docs/1_requirements/20251108_[Active]_requirements.md',
    '- docs/2_architecture/20251116_[Active]_system_architecture.md',
  ].join('\n');
}

export default async function DocsPage() {
  const content = await getMarkdownContent();

  return (
    <div className="container mx-auto py-6 space-y-6">
      <header className="space-y-2">
        <h1 className="text-3xl font-bold">用户使用文档</h1>
        <p className="text-muted-foreground">
          欢迎使用基本面分析系统。本文档将帮助您快速上手并充分利用系统的各项功能。
        </p>
      </header>
      <Card>
        <CardContent className="p-6">
          <article className="markdown-body" style={{
            boxSizing: 'border-box',
            minWidth: '200px',
            maxWidth: '980px',
            margin: '0 auto',
            padding: '0'
          }}>
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
            >
              {content}
            </ReactMarkdown>
          </article>
        </CardContent>
      </Card>
    </div>
  );
}