/**
 * HTTP handlers for `/api/apps`, `/api/apps/:id`, `/api/apps/:id/dashboards/:did`,
 * `/api/persona`. Designed to be invoked from `local-runtime.ts`'s request
 * dispatcher — returns `true` if the request was handled, `false` otherwise.
 */
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { ResearchPlan as AppResearchPlan } from '@duckcodeailabs/dql-agent';
import { type AppDocument, type DashboardDisplayMetadata, type DashboardDocument, type DashboardGridItem } from '@duckcodeailabs/dql-core';
import { LocalAppStorage, type LocalAppInvestigation, type LocalAppInvestigationIntent, type LocalAppInvestigationReportSection } from '@duckcodeailabs/dql-project';
interface Ctx {
    req: IncomingMessage;
    res: ServerResponse;
    url: URL;
    path: string;
    projectRoot: string;
    executeSql?: (sql: string) => Promise<unknown>;
    generateInvestigationSql?: (input: AppInvestigationGenerationRequest) => Promise<AppInvestigationGenerationResult>;
    runNotebook?: (appId: string, notebookPath: string) => Promise<void>;
    /** Grounded ReAct research planner (P4) — supplied by the runtime, which holds the
     *  metric/block catalog. Lets the App ask lane decide + offer real follow-ups. */
    planResearch?: (input: {
        question: string;
        isFollowUp?: boolean;
    }) => Promise<AppResearchPlan>;
}
export declare function handleAppsApi(ctx: Ctx): Promise<boolean>;
type AppListEntry = {
    id: string;
    name: string;
    filePath: string;
    domain: string;
    subdomain?: string;
    groups: string[];
    description?: string;
    audience?: string;
    lifecycle: NonNullable<AppDocument['lifecycle']>;
    certification: 'certified' | 'uncertified';
    status?: 'ready' | 'empty' | 'review';
    storage: 'shared' | 'mine' | 'template';
    visibility: NonNullable<AppDocument['visibility']>;
    owners: string[];
    tags: string[];
    members: number;
    roles: number;
    policies: number;
    schedules: number;
    dashboards: Array<{
        id: string;
        title: string;
    }>;
    notebooks: Array<{
        path: string;
        title?: string;
        role: 'source' | 'analysis' | 'supporting';
        visibility: NonNullable<AppDocument['visibility']>;
    }>;
    drafts: Array<{
        path: string;
        name: string;
        reviewStatus?: string;
    }>;
    aiPins: number;
    investigations: number;
    homepage?: AppDocument['homepage'];
};
declare function collectAppsList(projectRoot: string): AppListEntry[];
interface AppRecommendationRequest {
    domain?: string;
    tags?: string[];
    purpose?: string;
    audience?: string;
    certifiedOnly?: boolean;
}
interface VisualizationRecommendationRequest {
    blockRef?: string;
    resultSchema?: unknown;
    rowSample?: Array<Record<string, unknown>>;
    rows?: Array<Record<string, unknown>>;
    appAudience?: string;
    audience?: string;
    prompt?: string;
    filters?: unknown;
    allowedVisualizations?: string[];
    component?: DashboardDisplayMetadata['component'];
    defaultVisualization?: string;
}
interface AppCreateRequest {
    name?: string;
    domain?: string;
    dashboardTitle?: string;
    subdomain?: string;
    groups?: string[];
    purpose?: string;
    audience?: string;
    visibility?: 'shared' | 'private' | 'template';
    lifecycle?: AppDocument['lifecycle'];
    tags?: string[];
    owners?: string[];
    selectedBlockIds?: string[];
}
interface AppGenerateRequest {
    prompt?: string;
    domain?: string;
    owner?: string;
    force?: boolean;
    selectedBlockIds?: string[];
    plannerMode?: 'deterministic' | 'ai_assisted';
    audience?: string;
    notebookPath?: string;
    existingAppId?: string;
}
interface AppAiBuildSession {
    id: string;
    status: 'ready' | 'error';
    createdAt: string;
    updatedAt: string;
    prompt: string;
    appId?: string;
    dashboardId?: string | null;
    generatedPaths: string[];
    plan?: unknown;
    validation?: unknown;
    warnings: string[];
    reviewTasks: string[];
    inputs: {
        domain?: string;
        owner?: string;
        audience?: string;
        notebookPath?: string;
        existingAppId?: string;
        selectedBlockIds: string[];
    };
    error?: string;
}
interface AppAskRequest {
    question?: string;
    dashboardId?: string;
    tileId?: string;
    blockId?: string;
    variables?: Record<string, unknown>;
    context?: unknown;
    runInvestigation?: boolean;
}
interface AppAskDecision {
    mode: 'answer' | 'analysis' | 'app_change' | 'metadata';
    reason: string;
    nextAction: string;
    requiresContext: boolean;
    usesCertifiedResult: boolean;
    confidence: number;
}
interface AppPromoteRequest {
    lifecycle?: AppDocument['lifecycle'];
}
interface DashboardTileRecommendationRequest extends VisualizationRecommendationRequest {
    tileId?: string;
}
interface AiPinCreateRequest {
    dashboardId?: string;
    tileId?: string;
    title?: string;
    answer?: string;
    question?: string;
    sql?: string;
    sourceTier?: string;
    certification?: 'certified' | 'ai_generated';
    reviewStatus?: 'needs_review' | 'draft_created' | 'certified' | 'rejected';
    refreshCadence?: 'none' | 'daily';
    chartConfig?: Record<string, unknown>;
    result?: unknown;
    citations?: unknown[];
    analysisPlan?: unknown;
    evidence?: unknown;
    followUps?: string[];
}
interface AppInvestigationCreateRequest {
    dashboardId?: string;
    sourceTileId?: string;
    sourceBlockId?: string;
    title?: string;
    question?: string;
    intent?: LocalAppInvestigationIntent;
    context?: unknown;
    generatedSql?: string;
    run?: boolean;
}
interface AppInvestigationRunRequest {
    question?: string;
    intent?: LocalAppInvestigationIntent;
    context?: unknown;
    generatedSql?: string;
    repairMode?: 'rebuild_from_certified';
}
interface AppInvestigationGenerationRequest {
    appId: string;
    dashboardId?: string;
    sourceTileId?: string;
    sourceBlockId?: string;
    title?: string;
    question: string;
    intent: LocalAppInvestigationIntent;
    context?: unknown;
    mode?: 'sql_and_memo' | 'memo_only';
    generatedSql?: string;
    metrics?: Record<string, unknown>;
    drivers?: Array<Record<string, unknown>>;
    resultPreviews?: unknown[];
    summaryHint?: string;
    recommendationHint?: string;
    sqlError?: string;
    sqlErrorKind?: SqlPreviewErrorKind;
    hasReportEvidence?: boolean;
}
interface AppInvestigationGenerationResult {
    sql?: string;
    answer?: string;
    result?: unknown;
    analysisPlan?: unknown;
    evidence?: unknown;
    citations?: unknown[];
    suggestedViz?: string;
    executionError?: string;
    providerUsed?: string;
}
interface BlockCandidate {
    id: string;
    name: string;
    domain: string;
    status: string;
    owner: string | null;
    tags: string[];
    path: string;
    lastModified: string;
    description: string;
    llmContext: string | null;
    chartType?: string;
    score: number;
    reasons: string[];
}
export declare function recommendBlocks(projectRoot: string, input: AppRecommendationRequest): BlockCandidate[];
export declare function recommendVisualization(projectRoot: string, input: VisualizationRecommendationRequest): {
    ok: true;
    display: DashboardDisplayMetadata;
    evidence: Array<{
        source: string;
        reason: string;
    }>;
    warnings: string[];
} | {
    ok: false;
    error: string;
};
export declare function generateAppPackage(projectRoot: string, input: AppGenerateRequest): Promise<{
    ok: true;
    plan: unknown;
    validation: unknown;
    generated: {
        paths: string[];
    };
    app: ReturnType<typeof collectAppsList>[number] | null;
    dashboardId: string | null;
} | {
    ok: false;
    error: string;
}>;
export declare function createAppAiBuildSession(projectRoot: string, input: AppGenerateRequest): Promise<AppAiBuildSession>;
export declare function getAppAiBuildSession(projectRoot: string, id: string): AppAiBuildSession | null;
interface AppAskSuccess {
    ok: true;
    route: 'certified_answer' | 'investigation' | 'app_change_proposal' | 'metadata_answer';
    answer: string;
    trustState: 'certified' | 'review_required' | 'draft_ready';
    reviewStatus: 'certified' | 'review_required' | 'draft_ready';
    citations: Array<{
        kind: string;
        name: string;
        path?: string;
    }>;
    followUps: string[];
    decision: AppAskDecision;
    investigation?: LocalAppInvestigation;
    proposal?: unknown;
    /** Grounded ReAct research plan (P4): the decision, steps, and follow-up options. */
    researchPlan?: AppResearchPlan;
}
type AppAskResult = AppAskSuccess | {
    ok: false;
    error: string;
};
/**
 * Ask the App a question. Routes to the right lane (certified answer / investigation /
 * app change / metadata) and — when the runtime supplies a research planner — enriches
 * the result with a grounded ReAct plan + smart follow-up options (the P4 loop), so the
 * panel can DECIDE and offer real next steps instead of generic strings.
 */
declare function askAppQuestion(ctx: Ctx, appId: string, input: AppAskRequest): Promise<AppAskResult>;
export declare function recommendDashboardTile(projectRoot: string, appId: string, dashboardId: string, input: DashboardTileRecommendationRequest): {
    ok: true;
    display: DashboardDisplayMetadata;
    filterBindings: DashboardGridItem['filterBindings'];
    parameterBindings: DashboardGridItem['parameterBindings'];
    sourceEvidence: DashboardGridItem['sourceEvidence'];
    trustState: NonNullable<DashboardGridItem['trustState']>;
    reviewStatus: NonNullable<DashboardGridItem['reviewStatus']>;
    evidence: Array<{
        source: string;
        reason: string;
    }>;
    warnings: string[];
} | {
    ok: false;
    error: string;
};
export declare function promoteAppForStakeholders(projectRoot: string, appId: string, input?: AppPromoteRequest): {
    ok: true;
    app: AppDocument;
    paths: string[];
    removedLocalTiles: number;
} | {
    ok: false;
    error: string;
};
declare function renderSqlTemplateParams(sql: string, values: Record<string, unknown>): {
    sql: string;
    unresolved: string[];
};
declare function unresolvedSqlTemplateParams(sql: string): string[];
export declare function createAppPackage(projectRoot: string, input: AppCreateRequest): {
    ok: true;
    app: ReturnType<typeof collectAppsList>[number];
    paths: string[];
    dashboardId: string;
} | {
    ok: false;
    error: string;
};
declare function runAppInvestigation(ctx: Ctx, storage: LocalAppStorage, investigation: LocalAppInvestigation, input?: AppInvestigationRunRequest | AppInvestigationCreateRequest): Promise<LocalAppInvestigation>;
declare function selectedBlockContext(context: unknown): Record<string, unknown> | null;
declare function buildMetricSnapshot(selected: Record<string, unknown> | null): Record<string, unknown>;
declare function buildPreviewMetricSnapshot(preview: Record<string, unknown>, fallbackTitle?: string): Record<string, unknown>;
declare function buildPreviewDriverCards(preview: Record<string, unknown>, intent: LocalAppInvestigationIntent): Array<Record<string, unknown>>;
declare function buildDeterministicInvestigationSql(projectRoot: string, input: {
    question: string;
    intent: LocalAppInvestigationIntent;
    selected: Record<string, unknown> | null;
    sourceBlockId?: string;
    context?: unknown;
}): {
    sql: string;
    sourceBlockPath: string;
    sourceBlockName: string;
} | undefined;
declare function runGeneratedSqlPreview(ctx: Ctx, generatedSql?: string): Promise<{
    preview?: Record<string, unknown>;
    error?: string;
    fatal?: boolean;
}>;
type SqlPreviewErrorKind = 'runtime_unavailable' | 'ai_generation_timeout' | 'timeout' | 'sql_repair' | 'safety' | 'unknown';
declare function classifySqlPreviewError(error?: string): SqlPreviewErrorKind | undefined;
declare function buildInvestigationSummary(intent: LocalAppInvestigationIntent, question: string, selected: Record<string, unknown> | null, metrics: Record<string, unknown>, drivers: Array<Record<string, unknown>>): string;
declare function buildInvestigationReportSections(input: {
    intent: LocalAppInvestigationIntent;
    question: string;
    context: unknown;
    selected: Record<string, unknown> | null;
    metrics: Record<string, unknown>;
    drivers: Array<Record<string, unknown>>;
    summary: string;
    recommendation: string;
    agentAnswer?: string;
    hasReportEvidence?: boolean;
    sqlError?: string;
    sqlErrorKind?: SqlPreviewErrorKind;
    baselineGap?: boolean;
}): LocalAppInvestigationReportSection[];
declare function investigationNarrativeAnswer(investigation: LocalAppInvestigation): string;
export declare function createDashboardForApp(projectRoot: string, appId: string, input: {
    id?: string;
    title?: string;
    description?: string;
}): {
    ok: true;
    dashboard: DashboardDocument;
    path: string;
} | {
    ok: false;
    error: string;
};
declare function createAiPinTile(projectRoot: string, appId: string, input: AiPinCreateRequest): {
    ok: true;
    pin: unknown;
    dashboard?: DashboardDocument;
    tile?: DashboardGridItem;
    deduped?: boolean;
} | {
    ok: false;
    error: string;
};
declare function loadAppById(projectRoot: string, id: string): {
    app: AppDocument;
    appDir: string;
    appPath: string;
    dashboards: Array<{
        id: string;
        title: string;
        description?: string;
        itemCount: number;
    }>;
    notebooks: AppListEntry['notebooks'];
    drafts: AppListEntry['drafts'];
    aiPins: unknown[];
    investigations: unknown[];
} | null;
export declare function listNotebookCandidates(projectRoot: string, app: AppDocument, appDir: string): Array<{
    path: string;
    title: string;
    attached: boolean;
    role?: 'source' | 'analysis' | 'supporting';
    visibility?: NonNullable<AppDocument['visibility']>;
    lastModified?: string;
}>;
export declare function createNotebookForApp(projectRoot: string, appId: string, input: {
    name?: string;
    title?: string;
    role?: string;
    visibility?: string;
    template?: string;
}): {
    ok: true;
    path: string;
    app: ReturnType<typeof loadAppById>;
    preview: unknown;
} | {
    ok: false;
    error: string;
};
export declare function previewNotebookForApp(projectRoot: string, appId: string, notebookPath: string): {
    ok: true;
    preview: unknown;
} | {
    ok: false;
    status: number;
    error: string;
};
export declare const __test__: {
    buildMetricSnapshot: typeof buildMetricSnapshot;
    buildPreviewDriverCards: typeof buildPreviewDriverCards;
    buildPreviewMetricSnapshot: typeof buildPreviewMetricSnapshot;
    buildDeterministicInvestigationSql: typeof buildDeterministicInvestigationSql;
    buildInvestigationSummary: typeof buildInvestigationSummary;
    buildInvestigationReportSections: typeof buildInvestigationReportSections;
    classifySqlPreviewError: typeof classifySqlPreviewError;
    investigationNarrativeAnswer: typeof investigationNarrativeAnswer;
    createAiPinTile: typeof createAiPinTile;
    runGeneratedSqlPreview: typeof runGeneratedSqlPreview;
    renderSqlTemplateParams: typeof renderSqlTemplateParams;
    unresolvedSqlTemplateParams: typeof unresolvedSqlTemplateParams;
    selectedBlockContext: typeof selectedBlockContext;
    runAppInvestigation: typeof runAppInvestigation;
    askAppQuestion: typeof askAppQuestion;
    collectAppsList: typeof collectAppsList;
    loadAppById: typeof loadAppById;
};
export {};
//# sourceMappingURL=apps-api.d.ts.map