// app/hail/[id]/interview/page.js — the Configuration Interview surface.
//
// Server shell: loads the session + existing responses (practitioner view) and
// renders the client capture form. Session-level controls (pause / resume /
// render transcript) are server actions. Every answer is classified at capture
// by the client form; restricted/refused are visually distinct.

import Link from 'next/link';
import { notFound, redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { AdminShell } from '../../../components/admin/admin-page.jsx';
import { getEngagement } from '../../../../lib/hail/engagements.js';
import {
  getInterview,
  listInterviews,
  listDisplayResponses,
  pauseInterview,
  resumeInterview,
  completeInterview,
  renderTranscriptArtifact,
} from '../../../../lib/hail/interview.js';
import InterviewForm from './interview-form.jsx';
import { requirePractitionerPage } from '../../hail-guard.js';

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

export default async function InterviewPage({ params, searchParams }) {
  await requirePractitionerPage();
  const { id } = await params;
  const sp = await searchParams;
  const engagement = getEngagement(id);
  if (!engagement) notFound();

  const sessions = listInterviews(id);
  const sessionId = sp?.session || sessions[0]?.id || null;
  const interview = sessionId ? getInterview(sessionId) : null;
  if (!interview) {
    return (
      <AdminShell kicker="madarX OS · HAIL" title="Configuration Interview" hideProjectSwitcher
        actions={<Link href={`/hail/${id}`} className="hail-btn">← Cockpit</Link>}>
        <p className="hail-hint">No interview session. Start one from the engagement cockpit.</p>
      </AdminShell>
    );
  }
  // Client-safe: restricted/refused values are redacted server-side before they
  // can cross into the browser payload.
  const responses = listDisplayResponses(interview.id, { include_practitioner_notes: true });

  async function sessionAction(formData) {
    'use server';
    await requirePractitionerPage();
    const action = String(formData.get('action') || '');
    if (action === 'pause') pauseInterview(interview.id);
    else if (action === 'resume') resumeInterview(interview.id);
    else if (action === 'complete') completeInterview(interview.id);
    else if (action === 'transcript') renderTranscriptArtifact(interview.id);
    revalidatePath(`/hail/${id}/interview`);
    redirect(`/hail/${id}/interview?session=${interview.id}`);
  }

  return (
    <AdminShell
      kicker="madarX OS · HAIL"
      title={`Interview — ${engagement.principal_name}`}
      description="Each answer is classified at capture. Restricted answers stay local and are never rendered into artifacts; declined answers are not stored."
      hideProjectSwitcher
      actions={
        <div className="hail-actions">
          <Link href={`/hail/${id}`} className="hail-btn">← Cockpit</Link>
          <form action={sessionAction} className="hail-inline-form">
            {interview.status === 'paused'
              ? <button name="action" value="resume" className="hail-btn">Resume</button>
              : <button name="action" value="pause" className="hail-btn">Pause</button>}
            <button name="action" value="transcript" className="hail-btn">Render transcript</button>
            {interview.status !== 'complete' && <button name="action" value="complete" className="hail-btn">Mark complete</button>}
          </form>
        </div>
      }
    >
      <InterviewForm interviewId={interview.id} engagementId={id} status={interview.status}
        sectionCursor={interview.section_cursor} responses={responses} />
    </AdminShell>
  );
}
