// app/hail/[id]/setup/page.js — dry-run setup package review.
//
// Shows the proposed madarX OS configuration as per-item cards. Nothing here is
// applied — promotion to live configuration happens only after the setup-package
// approval gate (Phase 5 applier). Secret items carry only a name, never a value.

import Link from 'next/link';
import { notFound } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { AdminShell, EmptyState, StatusPill } from '../../../components/admin/admin-page.jsx';
import { getEngagement } from '../../../../lib/hail/engagements.js';
import { getSetupPackage } from '../../../../lib/hail/setup-package.js';
import { applySetupPackage } from '../../../../lib/hail/setup-applier.js';
import { requirePractitionerPage } from '../../hail-guard.js';

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

const RISK_TONE = { low: 'neutral', medium: 'info', high: 'warning', irreversible_external: 'danger', blocked: 'danger' };

export default async function SetupReviewPage({ params }) {
  const session = await requirePractitionerPage();
  const { id } = await params;
  const engagement = getEngagement(id);
  if (!engagement) notFound();
  const pkg = getSetupPackage(id);
  // Whether the package has cleared the setup-package approval gate. getSetupPackage
  // returns only the dry-run draft; once approved it surfaces as approved/applied
  // via a direct lookup of the latest package for this engagement.
  const applyable = pkg?.has_package && ['approved', 'partially_applied'].includes(pkg.status);

  async function applyAction() {
    'use server';
    const s = await requirePractitionerPage();
    if (pkg?.package_id) applySetupPackage(pkg.package_id, { user_id: s.user_id || null });
    revalidatePath(`/hail/${id}/setup`);
  }

  return (
    <AdminShell
      kicker="madarX OS · HAIL"
      title={`Setup review (dry-run) — ${engagement.principal_name}`}
      description="A dry-run proposal of the madarX OS configuration this engagement needs. Nothing is applied until the setup-package approval gate; every irreversible item still gates individually."
      hideProjectSwitcher
      actions={<Link href={`/hail/${id}`} className="hail-btn">← Cockpit</Link>}
    >
      {!pkg?.has_package ? (
        <EmptyState title="No setup package yet">
          Synthesize the blueprint to author a dry-run setup package.
        </EmptyState>
      ) : (
        <div className="hail-panel">
          <div className="hail-panel-head">
            <p className="hail-hint">Package v{pkg.version} · generated by {pkg.generated_by || '—'} · {pkg.items.length} item(s). Status: <strong>{pkg.status.replace('_', ' ')}</strong>.</p>
            {applyable && (
              <form action={applyAction}>
                <button type="submit" className="hail-btn hail-btn-primary">{pkg.status === 'partially_applied' ? 'Resume apply' : 'Promote to live config'}</button>
              </form>
            )}
          </div>
          {pkg.status === 'dry_run' && <p className="hail-hint">Dry-run — nothing applied. Promotion requires the setup-package approval gate; once approved, the apply runs each item through its own gate (irreversible items always gate individually).</p>}
          <div className="hail-setup-grid">
            {pkg.items.map((it) => (
              <div key={it.ref} className="hail-setup-card">
                <div className="hail-answer-head">
                  <span className="hail-answer-key">{it.type}</span>
                  <StatusPill tone={RISK_TONE[it.risk] || 'neutral'}>{it.risk}</StatusPill>
                  <span className="hail-badge tone-neutral">{it.apply_status}</span>
                </div>
                <div className="hail-mono">{it.ref}</div>
                {it.type === 'secret'
                  ? <p className="hail-hint">Secret request — value collected separately, never stored in this package.</p>
                  : <pre className="hail-setup-spec">{JSON.stringify(it.spec, null, 2)}</pre>}
              </div>
            ))}
          </div>
        </div>
      )}
    </AdminShell>
  );
}
