/**
 * Type definitions for Document Validation Rules feature.
 *
 * Validation rules define automated checks that run when documents are uploaded.
 * Each rule contains an LLM prompt that analyzes the document and may produce
 * ClarificationItems when issues are found.
 */
import type { ClarificationType, ClarificationResponseOption, ClarificationItem } from './clarification.js';
/** When a validation rule should execute */
export type ValidationCheckType = 'immediate' | 'backoffice';
/** What kind of validation logic to run */
export type ValidationType = 'llm_prompt' | 'periodic_coverage';
/** Cadence options for periodic coverage rules */
export type Cadence = 'quarterly' | 'monthly' | 'biweekly' | 'fortnightly';
/** How periodic cycles align within the expected range */
export type Alignment = 'calendar_aligned' | 'flexible';
/** Ordered list of variable references (e.g. ['@tenant_start_date', '@Beginning_Of_Tax_Year']).
 *  First non-empty resolved value wins. */
export type VariableChain = string[];
/** A gap (missing period) detected by a periodic coverage rule.
 *  Both `start` and `end` are inclusive — the gap covers every day from start through end. */
export interface ValidationGap {
    /** ISO date (YYYY-MM-DD) of the first uncovered day (inclusive) */
    start: string;
    /** ISO date (YYYY-MM-DD) of the last uncovered day (inclusive) */
    end: string;
}
/** Configuration for a periodic_coverage rule. The expected coverage window
 *  runs from the resolved `period_start` to the resolved `period_end`, partitioned
 *  into cycles by `cadence` + `alignment`. */
export interface CoverageConfig {
    /** How often a document is expected within the period */
    cadence: Cadence;
    /** Whether cycles snap to calendar boundaries or tile from period_start */
    alignment: Alignment;
    /** Variable chain resolving to the expected window's start (ISO YYYY-MM-DD).
     *  First non-empty value wins. Rule skips if all entries resolve null. */
    period_start: VariableChain;
    /** Variable chain resolving to the expected window's end (ISO YYYY-MM-DD).
     *  First non-empty value wins. Rule skips if all entries resolve null. */
    period_end: VariableChain;
}
/** A validation rule definition stored in the database */
export interface ValidationRule {
    /** Unique UUID primary key (system-generated) */
    id: string;
    /** Human-friendly rule identifier (unique, used in field references) */
    rule_id: string;
    /** Human-readable rule name */
    name: string;
    /** Optional description of what this rule checks */
    description?: string;
    /** Document type / category this rule applies to (e.g., "payg_summary", "bank_statement") */
    document_type: string;
    /** @deprecated Assign rules via `validation_rules` on fields/groups instead. Kept as fallback. */
    target_field_id?: string;
    /** @deprecated Assign rules via `validation_rules` on fields/groups instead. Kept as fallback. */
    target_label?: string;
    /** LLM prompt with {{variable}} placeholders */
    prompt: string;
    /** Which clarification template to use when an issue is found */
    clarification_type: ClarificationType;
    /** Whether this rule is active */
    enabled: boolean;
    /** Execution priority (lower = earlier, default: 100) */
    priority?: number;
    /** When this rule should execute: 'immediate' (on file upload), 'backoffice' (batch review), or unset (both). */
    check_type?: ValidationCheckType;
    /** Validation logic kind. Defaults to 'llm_prompt' for back-compat. */
    validation_type?: ValidationType;
    /** Configuration for periodic_coverage rules. Required when validation_type === 'periodic_coverage'. */
    coverage?: CoverageConfig;
    /** Custom issue description (overrides template default) */
    custom_issue_description?: string;
    /** Custom action description (overrides template default) */
    custom_action_description?: string;
    /** Custom response options (overrides template defaults) */
    custom_response_options?: ClarificationResponseOption[];
    /** Reference to a configured response set (replaces custom_response_options) */
    response_set_id?: string;
    /** Scope filter for multi-tenant setups */
    scope_id?: string | null;
    /**
     * Computed by the editor's data hook in two-tier mode; NOT persisted.
     * - 'global' — record has scope_id=null and no override exists in the current scope
     * - 'override' — record has scope_id=current_scope and shadows a same-rule_id global
     * - 'scope_only' — record has scope_id=current_scope with no matching global
     * Undefined in single-tier mode (when `include_globals` is false or unset).
     */
    origin?: 'global' | 'override' | 'scope_only';
    /** ISO timestamp when created */
    created_at: string;
    /** ISO timestamp of last update */
    changed_at: string;
}
/** Database record format for validation rules (element stored as JSON string) */
export interface ValidationRuleRecord {
    /** Database primary key (UUID) */
    id: string;
    /** Human-friendly rule identifier */
    rule_id: string;
    /** Scope filter */
    scope_id: string | null;
    /** Document type / category */
    document_type: string;
    /** Rule name */
    name: string;
    /** JSON-serialized rule data (everything except id, rule_id, scope_id, document_type, name, timestamps) */
    rule_data: string;
    /** ISO timestamp when created */
    created_at: string;
    /** ISO timestamp of last update */
    changed_at: string;
}
/** A slash command for the prompt editor (e.g., /check_coverage) */
export interface PromptCommand {
    /** The trigger text (e.g., "/check_coverage") */
    trigger: string;
    /** Display label */
    label: string;
    /** Prompt template that gets inserted */
    template: string;
    /** Optional description shown in autocomplete */
    description?: string;
}
/** A variable reference for the prompt editor (e.g., @field_list) */
export interface PromptVariable {
    /** The trigger text (e.g., "@field_list") */
    trigger: string;
    /** Display label */
    label: string;
    /** Description of what this variable resolves to */
    description?: string;
}
/** Configuration for prompt editor commands and variables */
export interface PromptEditorConfig {
    /** Slash commands available in the prompt editor */
    commands: PromptCommand[];
    /** Variable references available in the prompt editor */
    variables: PromptVariable[];
}
/** An action entry from the rule actions config file */
export interface RuleActionEntry {
    action: string;
    action_label: string;
    action_description: string;
    technical_description: string;
    source_data: string;
}
/** A variable entry from the rule actions config file */
export interface RuleVariableEntry {
    variable: string;
    variable_label: string;
    variable_description: string;
    technical_description: string;
    source_data: string;
    format?: string;
}
/** Schema for config/app_config_rule_actions.json */
export interface RuleActionsConfig {
    actions: RuleActionEntry[];
    variables: RuleVariableEntry[];
}
/** A rule prepared for execution with resolved variables */
export interface ValidationRuleExecution {
    /** Original rule ID */
    rule_id: string;
    /** Rule name for error reporting */
    name: string;
    /** Fully substituted prompt (variables resolved) */
    prompt: string;
    /** Target field ID for the resulting clarification */
    target_field_id: string;
    /** Target field label for display */
    target_label: string;
    /** Template to use for resulting clarification */
    clarification_type: ClarificationType;
    /** Custom issue description override */
    custom_issue_description?: string;
    /** Custom action description override */
    custom_action_description?: string;
    /** Custom response options override */
    custom_response_options?: ClarificationResponseOption[];
    /**
     * Which phase this rule executes in. When set on the execution, the server
     * stamps the ValidationRuleResult with the same value so the UI can filter
     * backoffice results away from the client view.
     */
    check_type?: ValidationCheckType;
}
/** A file entry for multi-file batch validation */
export interface ValidationFileEntry {
    /** File ID for enriching doc_references */
    file_id: string;
    /** File name for context */
    file_name: string;
    /** MIME type of the file */
    mime_type: string;
    /** URL to download the file */
    download_url?: string;
    /** Base64-encoded file content (preferred over download_url) */
    file_b64?: string;
}
/** Request payload for the validation route handler */
export interface ValidationRequest {
    /** Base64-encoded file content (preferred over download_url) */
    file_b64?: string;
    /** File name for context */
    file_name: string;
    /** MIME type of the file */
    mime_type: string;
    /** URL to download the file (fallback if file_b64 not provided) */
    download_url?: string;
    /** Rules to execute against this document */
    rules: ValidationRuleExecution[];
    /** Additional variables for prompt substitution */
    variables?: Record<string, string>;
    /** Content tag from hazo_files (used for document_type matching and as {{document_type}} variable) */
    content_tag?: string;
    /** Multi-file batch mode: array of files to validate collectively */
    files?: ValidationFileEntry[];
    /** 'batch' triggers collective multi-file evaluation; default 'single' */
    mode?: 'single' | 'batch';
}
/**
 * A single discovered issue within a rule result. A passed check has an empty
 * issues[] on the parent result; any entry here represents one distinct
 * violation. All content fields below are first-class — the LLM is instructed
 * to populate them directly via the response_wrapper in hazo_prompts.
 */
export interface ValidationIssue {
    /**
     * Stable identifier within the rule. Deterministic — the same input row
     * produces the same id across re-runs so persisted client responses
     * re-attach correctly.
     */
    issue_id: string;
    /** Human-readable description shown to the agent/client. */
    issue_description: string;
    /** Monetary amount referenced by this issue (e.g. "$437.47"). */
    amount?: string;
    /** Date or date range referenced by this issue. */
    date?: string;
    /**
     * Property address the issue relates to (rental property scenarios).
     * Used by the relevance check to verify response files reference the
     * right property when the client owns multiple properties.
     */
    property_address?: string;
    /**
     * Kind of vendor expected as evidence for this issue (e.g. "electrician",
     * "plumber"). Forwarded to the relevance check as expectation.context.vendor_hint.
     */
    vendor_hint?: string;
    /**
     * Short human label for the expense category the issue is about
     * (e.g. "Electrical Repairs"). Forwarded to the relevance check as
     * expectation.context.expense_label.
     */
    expense_label?: string;
    /** Longer explanation of why this is an issue (optional). */
    reason?: string;
    /** Client-facing comment the LLM drafted — suitable to surface verbatim to the client. */
    client_comment?: string;
    /** Per-issue confidence score (0-1). */
    confidence?: number;
    /** Client's resolution to this specific issue. */
    user_resolution?: {
        response_choice?: string;
        user_comment?: string;
        file_ids?: string[];
    };
    /** Whether the agent has sent this specific issue back to the client. */
    sent_back?: boolean;
    /** Whether the agent has accepted this specific issue's resolution. */
    accepted?: boolean;
    /** Issue kind. Defaults to 'file_issue' for back-compat. 'missing_file' indicates a coverage gap. */
    kind?: 'file_issue' | 'missing_file';
    /** Gap (date range) for missing_file issues */
    gap?: ValidationGap;
}
/**
 * Result from a single rule execution. Unified shape (v4+): `issues` is always
 * present. A passed check is `{ issues: [] }` with an optional `summary`. A
 * failed check has one or more entries in `issues`.
 */
export interface ValidationRuleResult {
    /** Rule ID that was executed */
    rule_id: string;
    /** Human-readable rule name (enriched from matching rule) */
    rule_name?: string;
    /**
     * Every discovered issue. Empty array = rule passed. Consumers derive
     * "has_issue" via `result.issues.length > 0`.
     */
    issues: ValidationIssue[];
    /**
     * Optional rule-level one-liner — typically shown when `issues` is empty to
     * explain why the check passed. Also populated when failing for an
     * additional summary above the issue list.
     */
    summary?: string;
    /** Rule-level confidence score (0-1). */
    confidence?: number;
    /** Raw LLM response for debugging. */
    raw_response?: string;
    /** Whether the user already resolved this rule during immediate validation (skipped re-validation) */
    user_resolved?: boolean;
    /** User's resolution details (when user_resolved is true). */
    user_resolution?: {
        response_choice?: string;
        user_comment?: string;
    };
    /** Whether this rule has been sent back to the client as a new clarification (pending client response). */
    sent_back?: boolean;
    /** The message sent to the client when this rule was sent back. */
    sent_back_message?: string;
    /** Whether the agent has accepted the client's resolution for this rule. */
    accepted?: boolean;
    /**
     * Which phase produced this result. 'immediate' results are visible to both
     * client and agent; 'backoffice' results are agent-only. Unset = treated as
     * 'immediate' for backward compatibility.
     */
    check_type?: ValidationCheckType;
    /** Structured outputs from per-file rules for downstream rules to consume.
     *  Today's only consumer is `periodic_coverage`, which reads
     *  `{ period_start: string, period_end: string }` (ISO YYYY-MM-DD) populated by
     *  date-extraction LLM rules. Promote to a discriminated union keyed by
     *  validation_type if/when other rule kinds need different shapes. */
    extracted_data?: Record<string, unknown>;
}
/** Response from the validation route handler */
export interface ValidationResponse {
    /** Overall success status */
    success: boolean;
    /** Created clarification items for rules that found issues */
    clarifications: ClarificationItem[];
    /** Individual rule results */
    rule_results: ValidationRuleResult[];
    /** Errors encountered during execution */
    errors?: Array<{
        rule_id: string;
        error: string;
    }>;
}
/** Minimal adapter interface for HazoConnectAdapter (avoids hard dependency on hazo_connect) */
export interface HazoConnectAdapterLike {
    query(builder: unknown, method?: string, body?: unknown): Promise<unknown>;
    rawQuery(endpoint: string, options?: RequestInit): Promise<unknown>;
    getConfig(): Promise<unknown>;
}
/** Options for the validation route handler factory */
export interface ValidationRouteOptions {
    /**
     * Path to the SQLite database for prompt lookup.
     * @deprecated Use `hazo_connect_adapter` instead. When adapter is provided, sqlite_path is ignored.
     */
    sqlite_path?: string;
    /**
     * HazoConnectAdapter from the consuming app.
     * Passed to hazo_llm_api for prompt lookup.
     * Works with any backend the adapter supports (SQLite, PostgREST, Supabase).
     */
    hazo_connect_adapter?: HazoConnectAdapterLike;
    /** Error callback (defaults to console.error) */
    on_error?: (error: unknown, context: string) => void;
}
/** Options for the use_file_validation hook */
export interface UseFileValidationOptions {
    /** Whether validation is enabled */
    enabled: boolean;
    /** API endpoint URL for validation */
    api_url: string;
    /** Rules to execute (typically fetched from DB) */
    rules: ValidationRule[];
    /** Current form data (for variable resolution) */
    form_data: Record<string, unknown>;
    /** Callback when new clarifications are created */
    on_clarifications_created?: (items: ClarificationItem[]) => void;
    /** Additional variables for prompt substitution */
    variables?: Record<string, string>;
    /**
     * Reverse map from rule ID to field info, built by build_rule_field_map().
     * When provided, overrides rule.target_field_id with the field that references the rule.
     */
    rule_field_map?: Record<string, {
        field_id: string;
        field_label: string;
    }>;
    /** Filter rules by check_type. When set, only rules matching this check_type (or defaulting to 'backoffice') are used. */
    check_type_filter?: ValidationCheckType;
}
/** Return type for the use_file_validation hook */
export interface UseFileValidationReturn {
    /** Trigger validation for a file. When content_tag_or_types is provided, only rules matching those document types (or 'general') are executed. Accepts a single string or array of document types. */
    validate_file: (file_b64: string, file_name: string, mime_type: string, content_tag_or_types?: string | string[]) => Promise<ClarificationItem[]>;
    /** Whether validation is currently in progress */
    is_validating: boolean;
    /** Last error message (if any) */
    last_error?: string;
}
//# sourceMappingURL=validation.d.ts.map