'use client';
/**
 * Client-side hook for triggering document validation.
 *
 * Calls the validation API endpoint with the uploaded file and rules,
 * and returns created ClarificationItems.
 */
import { useState, useCallback, useMemo } from 'react';
/**
 * Convert a ValidationRule to a ValidationRuleExecution for the API.
 * Performs client-side variable substitution where possible.
 *
 * Field resolution priority:
 * 1. rule_field_map[rule.rule_id] (field/group-level assignment via validation_rules)
 * 2. rule.target_field_id (deprecated, backward compat)
 * 3. '__document' (fallback for document-wide rules)
 */
function rule_to_execution(rule, variables, rule_field_map) {
    // Substitute known variables in the prompt
    let prompt = rule.prompt;
    for (const [key, value] of Object.entries(variables)) {
        prompt = prompt.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
    }
    // Resolve target field: map > rule.target_field_id > '__document'
    const mapping = rule_field_map?.[rule.rule_id];
    const target_field_id = mapping?.field_id ?? rule.target_field_id ?? '__document';
    const target_label = mapping?.field_label ?? rule.target_label ?? rule.name;
    return {
        rule_id: rule.rule_id,
        name: rule.name,
        prompt,
        target_field_id,
        target_label,
        clarification_type: rule.clarification_type,
        custom_issue_description: rule.custom_issue_description,
        custom_action_description: rule.custom_action_description,
        custom_response_options: rule.custom_response_options,
    };
}
/**
 * Hook for triggering document validation against uploaded files.
 *
 * Usage:
 * ```tsx
 * const { validate_file, is_validating, last_error } = use_file_validation({
 *   enabled: true,
 *   api_url: '/api/validation',
 *   rules: validation_rules,
 *   form_data: form_data,
 *   on_clarifications_created: (items) => { ... },
 * });
 *
 * // When a file is uploaded:
 * const clarifications = await validate_file(file_b64, 'document.pdf', 'application/pdf');
 * ```
 */
export function use_file_validation(options) {
    const { enabled, api_url, rules, form_data, on_clarifications_created, variables: extra_variables, rule_field_map, check_type_filter, } = options;
    const [is_validating, set_is_validating] = useState(false);
    const [last_error, set_last_error] = useState();
    // Filter to only enabled rules, optionally by check_type
    const enabled_rules = useMemo(() => {
        let filtered = rules.filter(r => r.enabled);
        if (check_type_filter) {
            filtered = filtered.filter(r => !r.check_type || r.check_type === check_type_filter);
        }
        return filtered;
    }, [rules, check_type_filter]);
    const validate_file = useCallback(async (file_b64, file_name, mime_type, content_tag_or_types) => {
        if (!enabled || enabled_rules.length === 0) {
            return [];
        }
        set_is_validating(true);
        set_last_error(undefined);
        try {
            // Normalize to array of document types
            const document_types = content_tag_or_types
                ? (Array.isArray(content_tag_or_types) ? content_tag_or_types : [content_tag_or_types])
                : undefined;
            // Filter rules by document_types when provided
            // A rule matches if:
            //   1. Its document_type is in the file's document_types, OR
            //   2. Its document_type is 'general' (catch-all — always matches), OR
            //   3. No document_types provided (match all enabled rules)
            const rules_to_execute = document_types
                ? enabled_rules.filter(r => document_types.includes(r.document_type) ||
                    r.document_type === 'general')
                : enabled_rules;
            if (rules_to_execute.length === 0) {
                return [];
            }
            // Build variables from form_data and extras
            const content_tag = document_types?.[0];
            const variables = {
                ...(extra_variables ?? {}),
                document_name: file_name,
                ...(content_tag ? { document_type: content_tag } : {}),
            };
            // Convert rules to executions
            const rule_executions = rules_to_execute.map(r => rule_to_execution(r, variables, rule_field_map));
            const request_body = {
                file_b64,
                file_name,
                mime_type,
                rules: rule_executions,
                variables,
                content_tag,
            };
            const response = await fetch(api_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(request_body),
            });
            if (!response.ok) {
                const error_data = await response.json().catch(() => ({}));
                throw new Error(error_data.errors?.[0]?.error || `HTTP ${response.status}`);
            }
            const result = await response.json();
            if (result.clarifications.length > 0) {
                on_clarifications_created?.(result.clarifications);
            }
            if (result.errors?.length) {
                console.warn('[use_file_validation] Some rules had errors:', result.errors);
            }
            return result.clarifications;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Validation failed';
            set_last_error(message);
            console.error('[use_file_validation] Error:', err);
            return [];
        }
        finally {
            set_is_validating(false);
        }
    }, [enabled, enabled_rules, api_url, extra_variables, on_clarifications_created, rule_field_map]);
    return {
        validate_file,
        is_validating,
        last_error,
    };
}
//# sourceMappingURL=use_file_validation.js.map