import { JSX } from 'react/jsx-runtime';

export declare type ApiStatus = {
    ok: boolean;
    appBuilder?: {
        hasOpenAiKey: boolean;
        environment: string;
        deploymentUrl: string | null;
    };
    error?: string;
};

export declare type BridgeCommandResult = {
    command: string;
    durationMs: number;
    exitCode: number;
    ok: boolean;
    stdout: string;
    stderr: string;
};

export declare type BridgeReadFilesResult = {
    ok: boolean;
    projectRoot?: string;
    files?: Array<{
        path: string;
        contents: string;
    }>;
    error?: string;
};

export declare type BridgeResult = {
    ok: boolean;
    projectRoot?: string;
    provider?: string;
    validation?: 'typecheck' | 'build' | 'write-policy-validation' | 'import-validation' | 'data-api-validation';
    changedFiles?: string[];
    summary?: string;
    changes?: Array<{
        kind: 'add' | 'edit' | 'remove';
        label: string;
    }>;
    files?: Array<{
        path: string;
        size: number;
    }>;
    generationMeta?: {
        model: string;
        strategy: string;
        reasoningEffort?: string;
        durationMs: number;
        outputChars?: number;
        fallbackFrom?: {
            strategy: string;
            reason: string;
        };
    };
    attempts?: Array<{
        label: string;
        ok: boolean;
        command: BridgeCommandResult;
    }>;
    command?: BridgeCommandResult;
    importValidation?: {
        ok: boolean;
        diagnostics: string[];
    };
    writePolicyValidation?: {
        ok: boolean;
        diagnostics: string[];
    };
    dataApiValidation?: {
        ok: boolean;
        diagnostics: string[];
    };
    telemetry?: {
        contextFileCount?: number;
        contextChars?: number;
        generatedFileCount?: number;
        generatedChars?: number;
        repairAttempts?: number;
    };
    filePlan?: BrowserSandboxFilePlan;
    error?: string;
};

export declare type BridgeWorkspaceContextResult = {
    ok: boolean;
    workspaceContext?: WorkspaceContext;
    error?: string;
};

declare type BrowserSandboxFilePlan = {
    intent: string;
    files: Array<{
        path: string;
        purpose: string;
        action: 'create' | 'edit';
    }>;
};

declare type BrowserSandboxRuntimeManifest = {
    id: string;
    name: string;
    execution: 'browser-sandbox';
    moduleSystem: string;
    cssPipeline: {
        mode: string;
        status: string;
    };
    packages: Array<{
        name: string;
        source: 'host' | 'runtime' | 'shim' | 'fallback';
        status: 'supported' | 'partial';
    }>;
    components: Array<{
        name: string;
        importPath: string;
        sourceFile: string;
        implementation: 'source' | 'shim';
        dependencies: string[];
    }>;
    limits: {
        writeScope: string[];
        editableGlobs: string[];
        unsupported: string[];
    };
};

declare type BuilderConversationContext = {
    messages: BuilderConversationMessage[];
    activeTarget?: string;
    lastSuccessfulRun?: {
        prompt: string;
        changedFiles: string[];
        summary?: string;
        filePlan?: BrowserSandboxFilePlan;
    };
    lastOperation?: DataAppOperationPlan;
    intentManifest?: DataAppIntentManifest;
};

declare type BuilderConversationMessage = {
    role: 'user' | 'assistant' | 'system';
    content: string;
};

export declare type BuilderTurn = {
    mode: BuilderTurnMode;
    message: string;
    operation?: DataAppOperationPlan;
    intentManifest?: DataAppIntentManifest;
    toolEvents?: Array<{
        tool: string;
        status: string;
        detail?: string;
    }>;
    requestedFiles?: string[];
    revision?: GeneratedRevision;
    artifacts?: DataAppBuilderArtifact[];
    uiActions?: DataAppBuilderUiAction[];
};

export declare type BuilderTurnMode = 'answer' | 'clarify' | 'edit' | 'read_files';

export declare type BuilderTurnResult = {
    ok: boolean;
    turn?: BuilderTurn;
    error?: string;
};

export declare function DataAppBuilder({ projectId, projectName, dataAppId, apiServiceUrl, adapters, }: DataAppBuilderProps): JSX.Element;

export declare type DataAppBuilderAdapters = {
    readStatus?: (options: {
        apiServiceUrl?: string;
        accessToken?: string;
        signal: AbortSignal;
    }) => Promise<ApiStatus>;
    runTurn?: (request: DataAppBuilderTurnRequest, options: {
        apiServiceUrl?: string;
        accessToken?: string;
        signal: AbortSignal;
        onProgress?: (progress: DataAppBuilderTurnProgress) => void;
    }) => Promise<BuilderTurn>;
    saveDraft?: (request: DataAppBuilderSaveDraftRequest, options: {
        apiServiceUrl?: string;
        accessToken?: string;
        signal: AbortSignal;
    }) => Promise<DataAppBuilderSaveDraftResult>;
    loadApp?: (request: {
        dataAppId: string;
    }, options: {
        apiServiceUrl?: string;
        accessToken?: string;
        signal: AbortSignal;
    }) => Promise<DataAppBuilderLoadedApp>;
    publish?: (request: DataAppBuilderPublishRequest, options: {
        apiServiceUrl?: string;
        accessToken?: string;
        signal: AbortSignal;
        onProgress?: (progress: DataAppBuilderPublishProgress) => void;
    }) => Promise<DataAppBuilderPublishResult>;
};

export declare type DataAppBuilderArtifact = DataAppBuilderDatasetInspectorArtifact;

declare type DataAppBuilderAttachment = {
    id: string;
    type: 'screenshot';
    name: string;
    imageUrl: string;
    mediaType: string;
    createdAt: number;
} | {
    id: string;
    type: 'dom-selection';
    name: string;
    text: string;
    createdAt: number;
};

export declare type DataAppBuilderDatasetInspectorArtifact = {
    id: string;
    type: 'dataset_inspector';
    title: string;
    domain: {
        id: string;
        name: string;
        label: string;
    };
    dataset: {
        id?: string | null;
        name: string;
        label?: string | null;
        analyticsRole?: string | null;
        primaryDateField?: string | null;
    };
    counts: {
        total: number;
        dimensions: number;
        measures: number;
        dates: number;
        identifiers: number;
        calculated: number;
    };
    fields: Array<{
        name: string;
        label?: string;
        role?: string;
        dataType?: string;
        source: 'physical' | 'calculated';
    }>;
};

export declare type DataAppBuilderLoadedApp = {
    id: string;
    projectId: string;
    title: string;
    description?: string | null;
    currentDataAppVersionId?: string | null;
    currentDataAppVersion?: DataAppBuilderLoadedVersion | null;
    dataAppVersions?: DataAppBuilderLoadedVersion[];
};

export declare type DataAppBuilderLoadedVersion = {
    id: string;
    dashboardId: string;
    version: number;
    status: string;
    manifest: DataAppManifest;
    sourceSnapshot?: DataAppSourceSnapshot | null;
    sourceRevision?: DataAppSourceRevision | null;
    bridgeWorkspaceHint?: string | null;
    createdAt?: string;
    updatedAt?: string;
};

export declare type DataAppBuilderProps = {
    projectId: string;
    projectName: string;
    dataAppId?: string | null;
    apiServiceUrl?: string;
    backHref?: string;
    onBack?: () => void;
    adapters?: DataAppBuilderAdapters;
};

declare type DataAppBuilderPublishAsset = {
    path: string;
    contentsBase64: string;
    contentType?: string;
};

export declare type DataAppBuilderPublishBuildResult = {
    manifest: DataAppManifest;
    validationStatus?: unknown;
    assets: DataAppBuilderPublishAsset[];
    entryFile: string;
    styleFiles?: string[];
    bridgeWorkspaceHint?: string | null;
};

export declare type DataAppBuilderPublishProgress = {
    phase: 'start' | 'build' | 'upload' | 'complete';
    label: string;
    detail?: string;
    assetIndex?: number;
    assetCount?: number;
};

export declare type DataAppBuilderPublishRequest = {
    projectId: string;
    dataAppId: string;
    draftId: string;
    title: string;
    description?: string | null;
    sourceSnapshot: DataAppSourceSnapshot;
    sourceRevision?: DataAppSourceRevision | null;
    bridgeWorkspaceHint?: string | null;
    validationStatus?: unknown;
    buildArtifacts: (options: {
        signal: AbortSignal;
        onProgress?: (progress: DataAppBuilderPublishProgress) => void;
    }) => Promise<DataAppBuilderPublishBuildResult>;
};

export declare type DataAppBuilderPublishResult = {
    dataAppId: string;
    versionId: string;
    version?: number;
    publishedAt?: string;
};

export declare type DataAppBuilderSaveDraftRequest = {
    projectId: string;
    dataAppId?: string | null;
    title?: string;
    description?: string | null;
    manifest: DataAppManifest;
    sourceSnapshot: DataAppSourceSnapshot;
    sourceRevision?: DataAppSourceRevision | null;
    validationStatus?: unknown;
    bridgeWorkspaceHint?: string | null;
};

export declare type DataAppBuilderSaveDraftResult = {
    dataAppId: string;
    draftId?: string;
    savedAt?: string;
};

export declare type DataAppBuilderTurnProgress = {
    phase: DataAppBuilderTurnProgressPhase;
    label: string;
    detail?: string;
};

declare type DataAppBuilderTurnProgressPhase = 'received' | 'authenticating' | 'routing' | 'inspecting_data' | 'reading_files' | 'planning_revision' | 'generating_code' | 'done';

export declare type DataAppBuilderTurnRequest = {
    projectId: string;
    message: string;
    currentFiles: NonNullable<BridgeReadFilesResult['files']>;
    workspaceContext: WorkspaceContext;
    conversationContext?: BuilderConversationContext;
    attachments?: DataAppBuilderAttachment[];
    diagnostics?: string[];
    repair?: boolean;
    allowFileReads?: boolean;
    generationModel: string;
    generationReasoningEffort?: ReasoningEffort;
    repairModel: string;
    repairReasoningEffort?: ReasoningEffort;
    stream?: boolean;
};

declare type DataAppBuilderUiAction = {
    type: 'open_dataset_inspector';
    artifactId: string;
};

export declare type DataAppIntentInput = {
    id: string;
    label: string;
    kind: 'filter' | 'control';
    field?: SemaphorFieldRef;
    sourceId?: string;
    operator?: SemaphorInputOperator;
    multi?: boolean;
    defaultValue?: unknown;
    affects?: string[];
};

export declare type DataAppIntentInteraction = {
    id: string;
    kind: 'filter_affects_view' | 'drilldown' | 'navigation' | 'selection';
    fromId: string;
    toIds: string[];
};

export declare type DataAppIntentLayout = {
    style?: 'dashboard' | 'workflow' | 'report' | 'custom';
    sections?: Array<{
        id: string;
        title?: string;
        viewIds: string[];
    }>;
};

export declare type DataAppIntentManifest = {
    schemaVersion: 'data-app-intent/v1';
    app: {
        title: string;
        description?: string;
        goal?: string;
    };
    sources: DataAppIntentSource[];
    inputs: DataAppIntentInput[];
    views: DataAppIntentView[];
    interactions?: DataAppIntentInteraction[];
    layout?: DataAppIntentLayout;
};

export declare type DataAppIntentSource = {
    id: string;
    label?: string;
    ref: SemaphorSourceRef;
    role?: 'primary' | 'lookup' | 'supporting';
};

export declare type DataAppIntentView = {
    id: string;
    title: string;
    description?: string;
    kind: DataAppIntentViewKind;
    /**
     * Canonical governed analytics question for this view. Generated React
     * should render it through react-semaphor/data-app-sdk hooks.
     */
    analytics?: SemaphorAnalyticsIntent;
    sourceIds?: string[];
    inputIds?: string[];
};

export declare type DataAppIntentViewKind = 'kpi' | 'line_chart' | 'bar_chart' | 'area_chart' | 'pie_chart' | 'table' | 'text' | 'custom';

export declare type DataAppManifest = {
    schemaVersion: 'data-app/v1';
    app?: {
        id?: string;
        name?: string;
        description?: string;
        createdWith?: string;
    };
    runtime?: {
        framework?: string;
        bundler?: string;
        entry?: string;
        styles?: string[];
        assetsBasePath?: string;
    };
    semaphor?: Record<string, unknown>;
    build?: Record<string, unknown>;
};

export declare type DataAppOperationPlan = {
    schemaVersion: 'data-app-operation/v1';
    type: DataAppOperationType;
    userGoal: string;
    target?: DataAppOperationTarget;
    /**
     * Shared analytics protocol intent for data-bearing work. This is the same
     * contract consumed by the Data App SDK/server executor, not a Data
     * App-specific query shape.
     */
    analyticsIntent?: SemaphorAnalyticsIntent;
    inputIds?: string[];
    requiredInspections?: Array<'data' | 'files' | 'preview' | 'diagnostics'>;
    confidence?: 'low' | 'medium' | 'high';
    rationale?: string;
};

export declare type DataAppOperationTarget = {
    id?: string;
    label?: string;
    kind?: string;
    filePath?: string;
    sourceId?: string;
    viewId?: string;
    inputId?: string;
    previousReference?: string;
};

export declare type DataAppOperationType = 'answer_question' | 'inspect_data' | 'inspect_files' | 'create_app' | 'add_view' | 'modify_view' | 'remove_view' | 'add_input' | 'modify_input' | 'remove_input' | 'change_layout' | 'change_style' | 'fix_error' | 'save_draft' | 'publish';

export declare type DataAppSourceRevision = {
    schemaVersion: 'data-app-source-revision/v1';
    snapshotHash: string;
    git?: {
        commit?: string;
        branch?: string;
        dirtyTreeHash?: string;
        isDirty?: boolean;
        remoteUrlHash?: string;
    };
    workspace?: {
        adapter: 'bridge' | 'codex' | 'cli';
        rootName?: string;
        pathHash?: string;
    };
    collectedAt: string;
};

export declare type DataAppSourceSnapshot = {
    schemaVersion: 'data-app-source-snapshot/v1';
    files: DataAppSourceSnapshotFile[];
    metadata?: Record<string, unknown>;
};

declare type DataAppSourceSnapshotFile = {
    path: string;
    contents: string;
    hash?: string;
};

export declare type GeneratedRevision = {
    provider?: string;
    summary?: string;
    changes?: BridgeResult['changes'];
    files: Array<{
        path: string;
        contents: string;
    }>;
    plan?: BrowserSandboxFilePlan;
    generationMeta?: BridgeResult['generationMeta'];
    attemptLabel?: string;
};

export declare type ReasoningEffort = 'low' | 'medium' | 'high';

declare type SemaphorAbsoluteTimeWindow = {
    kind: 'absolute';
    start: string;
    end: string;
};

declare type SemaphorAggregateFunction = 'SUM' | 'COUNT' | 'AVG' | 'MIN' | 'MAX' | 'MEDIAN' | 'DISTINCT';

declare type SemaphorAnalyticsFilter = SemaphorAnalyticsValueFilter | SemaphorAnalyticsNullFilter;

declare type SemaphorAnalyticsFilterBase = {
    id?: string;
    field: SemaphorFieldRef;
    /**
     * Controls where the filter is applied in an aggregate query.
     *
     * `row` means pre-aggregation filtering (`WHERE`).
     * `aggregate` means post-aggregation filtering (`HAVING`) and is valid only
     * for measure fields the execution engine can aggregate safely.
     */
    scope?: 'row' | 'aggregate';
};

declare type SemaphorAnalyticsFilterOperator = SemaphorInputOperator | 'not_contains' | 'is_null' | 'is_not_null';

declare type SemaphorAnalyticsIntent = SemaphorMetricIntent | SemaphorRecordsIntent | SemaphorInputOptionsIntent | SemaphorSqlIntent;

declare type SemaphorAnalyticsNullFilter = SemaphorAnalyticsFilterBase & {
    operator: SemaphorAnalyticsNullFilterOperator;
    values?: never;
};

declare type SemaphorAnalyticsNullFilterOperator = 'is_null' | 'is_not_null';

declare type SemaphorAnalyticsValueFilter = SemaphorAnalyticsFilterBase & {
    operator?: SemaphorAnalyticsValueFilterOperator;
    values: unknown[];
};

declare type SemaphorAnalyticsValueFilterOperator = Exclude<SemaphorAnalyticsFilterOperator, 'is_null' | 'is_not_null'>;

declare type SemaphorDialect = 'postgres' | 'mysql' | 'mssql' | 'snowflake' | 'clickhouse' | 'bigquery' | 'redshift' | 'duckdb' | 'sqlite' | 'unknown';

declare type SemaphorFieldRef = {
    name: string;
    label?: string;
    role?: 'dimension' | 'measure' | 'date' | 'id' | 'unknown';
    dataType?: 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'unknown';
    source?: SemaphorSourceRef;
    aggregate?: SemaphorAggregateFunction;
};

declare type SemaphorInputBinding = {
    inputId: string;
    kind?: 'filter' | 'control';
    controlRole?: 'grain' | 'metric' | 'dimension' | 'aggregation' | 'sqlParam';
    operator?: SemaphorInputOperator;
    field?: SemaphorFieldRef;
};

declare type SemaphorInputOperator = '=' | '!=' | 'in' | 'not_in' | 'contains' | 'not_contains' | 'between' | 'not_between' | '>' | '>=' | '<' | '<=';

declare type SemaphorInputOptionsIntent = {
    kind: 'inputOptions';
    version?: SemaphorProtocolVersion;
    id?: string;
    label?: string;
    source: SemaphorSourceRef;
    field: SemaphorFieldRef;
    search?: string;
    limit?: number;
};

declare type SemaphorMetricAnalysis = {
    kind: 'period_change';
    orderBy?: 'absolute_change' | 'positive_change' | 'negative_change' | 'period';
    direction?: 'increase' | 'decrease' | 'both';
    timeWindow?: SemaphorTimeWindow;
};

declare type SemaphorMetricIntent = {
    kind: 'metric';
    version?: SemaphorProtocolVersion;
    id?: string;
    source: SemaphorSourceRef;
    metrics: SemaphorFieldRef[];
    primaryMetric?: SemaphorFieldRef;
    label?: string;
    dateField?: SemaphorFieldRef;
    timeGrain?: SemaphorTimeGrain;
    timeWindow?: SemaphorTimeWindow;
    dimensions?: SemaphorFieldRef[];
    filters?: SemaphorAnalyticsFilter[];
    comparison?: {
        kind: 'previous_period' | 'previous_year' | 'target';
        targetValue?: number;
    };
    analysis?: SemaphorMetricAnalysis;
    orderBy?: {
        field: SemaphorFieldRef;
        direction: 'asc' | 'desc';
    };
    inputs?: SemaphorInputBinding[];
    limit?: number;
};

declare type SemaphorPaginationRequest = {
    page: number;
    pageSize: number;
};

declare type SemaphorProtocolVersion = 1;

declare type SemaphorRecordsIntent = {
    kind: 'records';
    version?: SemaphorProtocolVersion;
    source: SemaphorSourceRef;
    id?: string;
    label?: string;
    fields: SemaphorFieldRef[];
    dateField?: SemaphorFieldRef;
    timeGrain?: SemaphorTimeGrain;
    timeWindow?: SemaphorTimeWindow;
    filters?: SemaphorAnalyticsFilter[];
    limit?: number;
    pagination?: SemaphorPaginationRequest;
    orderBy?: {
        field: SemaphorFieldRef;
        direction: 'asc' | 'desc';
    };
    inputs?: SemaphorInputBinding[];
};

declare type SemaphorRelativeTimeWindow = {
    kind?: 'relative';
    unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
    value: number;
    anchor?: 'now' | 'latest_available';
    completeness?: 'include_partial' | 'complete_periods';
};

declare type SemaphorSourceRef = {
    kind: 'semantic';
    domainId: string;
    datasetName: string;
    datasetId?: string;
    label?: string;
    connectionId?: string;
} | {
    kind: 'physical';
    connectionId: string;
    connectionType?: string;
    tableName: string;
    databaseName?: string;
    schemaName?: string;
    label?: string;
    dialect?: SemaphorDialect;
} | {
    kind: 'sql';
    connectionId: string;
    dialect?: SemaphorDialect;
    label?: string;
};

declare type SemaphorSqlIntent = {
    kind: 'sql';
    version?: SemaphorProtocolVersion;
    id?: string;
    label?: string;
    source: Extract<SemaphorSourceRef, {
        kind: 'sql';
    }>;
    sql: string;
    defaultParameters?: Record<string, unknown>;
    pythonCode?: string;
    limit?: number;
    pagination?: SemaphorPaginationRequest;
    rationale?: string;
    fields?: SemaphorFieldRef[];
    inputs?: SemaphorInputBinding[];
};

declare type SemaphorTimeGrain = 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';

declare type SemaphorTimeWindow = SemaphorRelativeTimeWindow | SemaphorAbsoluteTimeWindow;

export declare type WorkspaceContext = {
    projectRoot?: string;
    framework?: string;
    packageManager?: string;
    runtimeManifest?: BrowserSandboxRuntimeManifest;
    packageJson?: {
        dependencies?: Record<string, string>;
        devDependencies?: Record<string, string>;
        scripts?: Record<string, string>;
    };
    componentsJson?: unknown;
    tsconfig?: {
        baseUrl?: string | null;
        paths?: Record<string, string[]>;
        jsx?: string | null;
        strict?: boolean | null;
        noUnusedLocals?: boolean | null;
        noUnusedParameters?: boolean | null;
    };
    files?: {
        source?: string[];
        root?: string[];
        snapshot?: string[];
        editable?: string[];
        editableGlobs?: string[];
        approvalRequiredGlobs?: string[];
        styleEntries?: string[];
        localModules?: string[];
    };
    validation?: {
        typecheck?: string | null;
        build?: string | null;
    };
    capabilities?: unknown;
};

export { }
