// app/hail/[id]/page.js — engagement cockpit.
//
// Lifecycle rail (Diagnostic → Blueprint → Pilot → Managed Layer), interview
// sessions, and entry to the Configuration Interview. Technical surfaces
// (engine case ids, runs) live on /runtime per the product convention.

import Link from 'next/link';
import { notFound, redirect } 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 { listInterviews, startInterview } from '../../../lib/hail/interview.js';
import { synthesizeDiagnostic, getDiagnosticDrafts } from '../../../lib/hail/diagnostic.js';
import { synthesizeBlueprint, getBlueprintDrafts } from '../../../lib/hail/blueprint.js';
import { syncLifecycleGates } from '../../../lib/hail/review-gates.js';
import { syncPilotState } from '../../../lib/hail/pilot.js';
import { startQuarterlyReview, listQuarterlyReviews, synthesizeReviewDelta } from '../../../lib/hail/quarterly-review.js';
import { LIFECYCLE_STAGES } from '../../../lib/hail/constants.js';
import { requirePractitionerPage } from '../hail-guard.js';

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

const STAGE_LABEL = { diagnostic: 'Diagnostic', blueprint: 'Blueprint', pilot: 'Pilot', managed_layer: 'Managed Layer' };
const IV_TONE = { in_progress: 'info', paused: 'warning', complete: 'success' };

export default async function EngagementCockpit({ params }) {
  await requirePractitionerPage();
  const { id } = await params;
  const engagement = getEngagement(id);
  if (!engagement) notFound();
  const interviews = listInterviews(id);
  const drafts = getDiagnosticDrafts(id);
  const blueprint = getBlueprintDrafts(id);
  const gates = syncLifecycleGates(engagement);
  const pilot = syncPilotState(engagement);
  const reviews = listQuarterlyReviews(id);

  async function startInterviewAction() {
    'use server';
    await requirePractitionerPage();
    const iv = startInterview({ engagement_id: id });
    revalidatePath(`/hail/${id}`);
    redirect(`/hail/${id}/interview?session=${iv.id}`);
  }

  async function synthesizeDiagnosticAction() {
    'use server';
    await requirePractitionerPage();
    await synthesizeDiagnostic({ engagement_id: id });
    revalidatePath(`/hail/${id}`);
  }

  async function synthesizeBlueprintAction() {
    'use server';
    await requirePractitionerPage();
    await synthesizeBlueprint({ engagement_id: id });
    revalidatePath(`/hail/${id}`);
  }

  async function startQuarterlyReviewAction() {
    'use server';
    await requirePractitionerPage();
    const caseRow = startQuarterlyReview(id);
    try { synthesizeReviewDelta(id); } catch { /* delta optional if no current package */ }
    revalidatePath(`/hail/${id}`);
    redirect(`/workflows/${caseRow.id}`);
  }

  const currentIndex = LIFECYCLE_STAGES.indexOf(engagement.current_stage);
  const diagnosticGate = gates.find((g) => g.gate_type === 'diagnostic_signoff');
  const blueprintGate = gates.find((g) => g.gate_type === 'blueprint_signoff');

  return (
    <AdminShell
      kicker="madarX OS · HAIL"
      title={engagement.principal_name}
      description={`${engagement.institution_type || 'Principal'} · accountable: ${engagement.accountable_human}`}
      hideProjectSwitcher
      actions={<Link href="/hail" className="hail-btn">← All engagements</Link>}
    >
      <ol className="hail-rail">
        {LIFECYCLE_STAGES.map((stage, i) => (
          <li key={stage} className={`hail-rail-step ${i < currentIndex ? 'is-done' : ''} ${i === currentIndex ? 'is-current' : ''}`}>
            <span className="hail-rail-dot" />
            <span className="hail-rail-label">{STAGE_LABEL[stage]}</span>
          </li>
        ))}
      </ol>

      <div className="hail-grid">
        <section className="hail-panel">
          <div className="hail-panel-head">
            <h2 className="hail-panel-title">Configuration Interview</h2>
            <form action={startInterviewAction}>
              <button type="submit" className="hail-btn hail-btn-primary">Start session</button>
            </form>
          </div>
          {interviews.length === 0 ? (
            <EmptyState title="No interview yet">
              The first hour every principal spends with HAIL is the Configuration Interview. Each answer is classified at capture.
            </EmptyState>
          ) : (
            <ul className="hail-list">
              {interviews.map((iv) => (
                <li key={iv.id} className="hail-list-row">
                  <Link href={`/hail/${id}/interview?session=${iv.id}`} className="hail-list-link">
                    <span className="hail-list-name">{iv.title}</span>
                    <span className="hail-list-meta">Section: {iv.section_cursor || '—'}</span>
                  </Link>
                  <StatusPill tone={IV_TONE[iv.status] || 'neutral'}>{iv.status.replace('_', ' ')}</StatusPill>
                </li>
              ))}
            </ul>
          )}
        </section>

        <section className="hail-panel">
          <div className="hail-panel-head">
            <h2 className="hail-panel-title">Diagnostic</h2>
            <form action={synthesizeDiagnosticAction}>
              <button type="submit" className="hail-btn">{drafts?.has_diagnostic ? 'Re-synthesize' : 'Synthesize'}</button>
            </form>
          </div>
          {!drafts?.has_diagnostic ? (
            <EmptyState title="No diagnostic yet">
              Run the interview, then synthesize the operating profile, role/capacity map, and friction map. Restricted answers are masked before any cloud engine sees them.
            </EmptyState>
          ) : (
            <div className="hail-diagnostic-summary">
              <dl className="hail-meta">
                <div><dt>Operating profile</dt><dd>v{drafts.version}</dd></div>
                <div><dt>Roles / capacities</dt><dd>{drafts.roles.length}</dd></div>
                <div><dt>Boundaries</dt><dd>{drafts.boundaries.length}</dd></div>
                <div><dt>Frictions</dt><dd>{drafts.frictions.length}</dd></div>
              </dl>
              {drafts.frictions.length > 0 && (
                <>
                  <h3 className="hail-subhead">Top frictions</h3>
                  <ul className="hail-list">
                    {drafts.frictions.slice(0, 4).map((f, i) => (
                      <li key={i} className="hail-list-row">
                        <span className="hail-list-name">{f.description}</span>
                        <StatusPill tone={f.risk_level === 'high' ? 'danger' : 'neutral'}>{f.risk_level || 'medium'}</StatusPill>
                      </li>
                    ))}
                  </ul>
                </>
              )}
              {diagnosticGate && (
                <p className="hail-hint">
                  Diagnostic sign-off: <strong>{diagnosticGate.decision.replace('_', ' ')}</strong>. Review gates are recorded for counsel/auditor in the engagement ledger.
                </p>
              )}
              <p className="hail-hint">Operating profile, role map, and friction map artifacts are in this engagement's project library.</p>
            </div>
          )}
        </section>

        <section className="hail-panel">
          <div className="hail-panel-head">
            <h2 className="hail-panel-title">Blueprint</h2>
            {drafts?.has_diagnostic && (
              <form action={synthesizeBlueprintAction}>
                <button type="submit" className="hail-btn">{blueprint?.has_blueprint ? 'Re-synthesize' : 'Synthesize'}</button>
              </form>
            )}
          </div>
          {!drafts?.has_diagnostic ? (
            <EmptyState title="Diagnostic first">
              Synthesize the diagnostic before the blueprint. The blueprint designs the governance matrix, agent roster, and a dry-run setup package from the approved diagnostic.
            </EmptyState>
          ) : !blueprint?.has_blueprint ? (
            <EmptyState title="No blueprint yet">
              Design the governed agent operating model and a dry-run setup package. Nothing is applied until the setup-package approval gate.
            </EmptyState>
          ) : (
            <div className="hail-diagnostic-summary">
              <dl className="hail-meta">
                <div><dt>Governance rules</dt><dd>{blueprint.governance_rules.length}</dd></div>
                <div><dt>Proposed agents</dt><dd>{blueprint.agent_blueprints.length}</dd></div>
                <div><dt>Setup items (dry-run)</dt><dd>{blueprint.setup_package?.items?.length || 0}</dd></div>
              </dl>
              <p className="hail-actions">
                <Link href={`/hail/${id}/governance`} className="hail-btn">Governance matrix</Link>
                <Link href={`/hail/${id}/setup`} className="hail-btn">Setup review</Link>
              </p>
              {blueprintGate && (
                <p className="hail-hint">Blueprint sign-off: <strong>{blueprintGate.decision.replace('_', ' ')}</strong>.</p>
              )}
            </div>
          )}
        </section>

        <section className="hail-panel">
          <h2 className="hail-panel-title">Pilot & Managed Layer</h2>
          {!pilot.pilot_launched ? (
            <EmptyState title="Pilot not launched">
              Once the setup package is applied and the pilot-launch gate is approved, the provisioned agents go live here.
            </EmptyState>
          ) : (
            <div className="hail-diagnostic-summary">
              <dl className="hail-meta">
                <div><dt>Pilot agents live</dt><dd>{pilot.agents.filter((a) => a.status === 'live').length} / {pilot.agents.length}</dd></div>
                <div><dt>Stage</dt><dd>{pilot.managed_layer ? 'Managed Layer' : 'Pilot'}</dd></div>
              </dl>
              <ul className="hail-list">
                {pilot.agents.map((a) => (
                  <li key={a.agent_slug} className="hail-list-row">
                    <span className="hail-list-name">{a.name}</span>
                    <StatusPill tone={a.status === 'live' ? 'success' : a.status === 'provisioned' ? 'info' : 'neutral'}>{a.status}</StatusPill>
                  </li>
                ))}
              </ul>
            </div>
          )}
          {pilot.managed_layer && (
            <p className="hail-actions">
              <form action={startQuarterlyReviewAction}>
                <button type="submit" className="hail-btn hail-btn-primary">Start quarterly review</button>
              </form>
            </p>
          )}
          {reviews.length > 0 && (
            <>
              <h3 className="hail-subhead">Quarterly reviews</h3>
              <ul className="hail-list">
                {reviews.map((r) => (
                  <li key={r.id} className="hail-list-row">
                    <Link href={`/workflows/${r.id}`} className="hail-list-link"><span className="hail-list-name">{r.title}</span></Link>
                    <StatusPill tone={r.status === 'complete' ? 'success' : 'info'}>{r.status}</StatusPill>
                  </li>
                ))}
              </ul>
            </>
          )}
        </section>

        <section className="hail-panel">
          <h2 className="hail-panel-title">Engagement</h2>
          <dl className="hail-meta">
            <div><dt>Confidentiality</dt><dd>{engagement.confidentiality_posture.replace(/_/g, ' ')}</dd></div>
            <div><dt>Current stage</dt><dd>{STAGE_LABEL[engagement.current_stage] || engagement.current_stage}</dd></div>
            <div><dt>Status</dt><dd>{engagement.status}</dd></div>
            <div><dt>Lifecycle case</dt><dd className="hail-mono">{engagement.process_case_id || '—'}</dd></div>
          </dl>
          <p className="hail-hint">Diagnostic, blueprint, and setup artifacts appear in this engagement's project library. Technical runtime detail lives on <Link href="/runtime" className="hail-inline-link">/runtime</Link>.</p>
        </section>
      </div>
    </AdminShell>
  );
}
