import fs from 'node:fs';
import path from 'node:path';
import { AdminShell, EmptyState, StatCard, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { ROOT } from '@/lib/paths.js';
import { listArtifacts, listRuns } from '@/lib/runtime.js';
import { reportingSnapshot } from '@/lib/delegation.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function fileInfo(relPath) {
  if (!relPath) return { exists: false, name: null, href: null };
  const full = path.resolve(ROOT, relPath);
  const relative = path.relative(ROOT, full);
  const insideRoot = relative && !relative.startsWith('..') && !path.isAbsolute(relative);
  const exists = insideRoot && fs.existsSync(full);
  const name = path.basename(full);
  const normalizedRel = relative.split(path.sep).join('/');
  const href = normalizedRel.startsWith('workspace/reports/') ? `/reports/${encodeURIComponent(name)}` : null;
  return { exists, name, href };
}

function previewText(item) {
  return String(item.preview || item.content || item.source_md || item.output || '').replace(/<[^>]+>/g, ' ').slice(0, 500);
}

export default function ReportsPage() {
  const runs = listRuns(80);
  const artifacts = listArtifacts(80);
  const reportRuns = runs.filter(run => String(run.kind || '').includes('report') || String(run.artifact || '').includes('reports'));
  const reporting = reportingSnapshot();

  return (
    <AdminShell
      title="Reports"
      description="madarX OS v1.0 runs, artifacts, and report browser with previews and download links where report files exist."
    >
      <section className="admin-stats">
        <StatCard label="Runs" value={runs.length} />
        <StatCard label="Artifacts" value={artifacts.length} />
        <StatCard label="Report-like runs" value={reportRuns.length} />
        <StatCard label="Blocked tasks" value={reporting.totals.blocked_tasks} />
      </section>

      <section className="admin-grid reports-layout">
        <div className="admin-panel">
          <div className="admin-panel-head"><span>Runs browser</span><small>Latest execution records.</small></div>
          {runs.length ? (
            <div className="admin-card-list compact">
              {runs.map(run => {
                const info = fileInfo(run.artifact);
                return (
                  <article className="admin-record compact" key={run.id}>
                    <div className="admin-record-top"><b>{run.title || run.kind}</b><StatusPill tone={run.status === 'complete' ? 'ready' : run.status === 'failed' ? 'danger' : 'warn'}>{run.status || 'complete'}</StatusPill></div>
                    <p>{previewText(run) || 'No preview text captured.'}</p>
                    <div className="admin-tool-meta"><span>{run.kind}</span><span>{run.agent || run.agent_id || 'system'}</span><span>{run.at}</span></div>
                    {info.exists && info.href ? <a className="admin-link" href={info.href}>Download {info.name}</a> : <small>{info.exists ? `File exists: ${info.name}` : 'No downloadable report file'}</small>}
                  </article>
                );
              })}
            </div>
          ) : <EmptyState title="No runs yet">Runs and generated reports will appear here.</EmptyState>}
        </div>

        <div className="admin-panel">
          <div className="admin-panel-head"><span>Artifacts browser</span><small>Generated documents and UI outputs.</small></div>
          {artifacts.length ? (
            <div className="admin-card-list compact">
              {artifacts.map(artifact => {
                const info = fileInfo(artifact.path);
                return (
                  <article className="admin-record compact" key={artifact.id}>
                    <div className="admin-record-top"><b>{artifact.title || artifact.path || artifact.kind}</b><StatusPill>{artifact.kind || 'artifact'}</StatusPill></div>
                    <p>{previewText(artifact) || artifact.path || 'No preview text captured.'}</p>
                    <div className="admin-tool-meta"><span>{artifact.agent_id || 'system'}</span><span>{artifact.created_at}</span></div>
                    {info.exists && info.href ? <a className="admin-link" href={info.href}>Download {info.name}</a> : <small>{info.exists ? `File exists: ${info.name}` : 'File missing or virtual artifact'}</small>}
                  </article>
                );
              })}
            </div>
          ) : <EmptyState title="No artifacts yet">Artifacts generated by agents and the main console will appear here.</EmptyState>}
        </div>
      </section>

      <section className="admin-grid reports-layout">
        <div className="admin-panel">
          <div className="admin-panel-head"><span>Operational views</span><small>tasks by status, blocked, stale, and run success rate.</small></div>
          <div className="admin-card-list compact">
            {reporting.tasks_by_status.map(row => (
              <div key={row.status} className="admin-record compact">
                <div className="admin-record-top"><b>{row.status}</b><StatusPill>{row.count}</StatusPill></div>
                <p>Tasks by status</p>
              </div>
            ))}
            {reporting.run_success_rate.slice(0, 5).map(row => (
              <div key={row.agent_id} className="admin-record compact">
                <div className="admin-record-top"><b>{row.agent_id}</b><StatusPill>{row.succeeded}/{row.total}</StatusPill></div>
                <p>Run success rate</p>
              </div>
            ))}
          </div>
        </div>

        <div className="admin-panel">
          <div className="admin-panel-head"><span>Audit views</span><small>manager delegation, workload across reports, and approval wait time.</small></div>
          <div className="admin-card-list compact">
            {reporting.manager_delegation.slice(0, 5).map(row => (
              <div key={row.manager_id || row.manager_name} className="admin-record compact">
                <div className="admin-record-top"><b>{row.manager_name || row.manager_id || 'unmanaged'}</b><StatusPill>{row.delegated_task_count}</StatusPill></div>
                <p>Delegation count by manager</p>
              </div>
            ))}
            {reporting.approval_latency.slice(0, 5).map(row => (
              <div key={row.approval_request_id} className="admin-record compact">
                <div className="admin-record-top"><b>{row.action_type}</b><StatusPill>{row.status}</StatusPill></div>
                <p>Approval wait time: {row.latency_seconds ?? 'pending'} seconds</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </AdminShell>
  );
}
