/*
 * vericull_core.h - Open-Source C11 / C++17 Native ABI Header for libvericull_core (v4.0.0)
 * SPDX-License-Identifier: MIT OR Apache-2.0
 * Copyright (c) 2026 RISCON Co., Ltd. and Vericull Contributors
 *
 * Zero-LLM, zero-dependency deterministic security & governance verification core:
 *   1. vericull_lex_inspect(_ex)    (language-aware C/C++/Rust/Go/TS-JS/Verilog byte-exact lexer)
 *   2. vericull_aho_corasick_sweep  (VCND 0x56434E44 comment-masked positive & negative byte spans)
 *   3. vericull_gbdt_eval           (VCSF-36 feature, 64-tree float32 GBDT + strict VC-R02 finite/DAG guard)
 *   4. vericull_pattern_recall      (VCPC BM25/IDF-weighted FNV-1a64 recall + CWE structural boost)
 *   5. vericull_adjudicate          (VC-R04 Wilson 95% lower-bound gate & VCVD SplitMix64 seal;
 *                                    ABI 401 legacy replay)
 *   6. vericull_adjudicate_402      (ABI 402 issuance: per-stage S3/S4 evidence with presence flags)
 */

#ifndef VERICULL_CORE_H
#define VERICULL_CORE_H

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/* ABI of the legacy-replay entry points (`vericull_aho_corasick_sweep`, `vericull_adjudicate`,
 * `vericull_pattern_recall`). Their signatures and struct layouts are unchanged since ABI 401. */
#define VERICULL_ABI_VERSION    401u
/* ABI 402 adds trusted lexer-mode selection, per-stage S3/S4 evidence with presence flags
 * (issuance semantics "vericull.stage-evidence.v2"), buffer-level lexer ambiguity reporting,
 * status-returning pattern recall and documented length caps. `vericull_abi_version()` returns
 * this value. */
#define VERICULL_ABI_VERSION_402 402u
#define VERICULL_NEEDLE_MAGIC   0x56434E44u /* "VCND": Vericull Claim Needle Descriptor */
#define VERICULL_VERDICT_MAGIC  0x56435644u /* "VCVD": Vericull Cryptographic Verdict Digest */
#define VERICULL_MAX_CLAIMS     32
#define VERICULL_MAX_NODES      32
#define VERICULL_NUM_FEATURES   36

/* Status codes. Every exported function that returns int32_t returns a value >= 0 on success
 * or one of these negative codes; no exported function lets a C++ exception escape. */
#define VERICULL_OK               0
#define VERICULL_E_NULL         (-1) /* required pointer is NULL (or NULL buffer with nonzero length) */
#define VERICULL_E_INVALID      (-2) /* invalid descriptor, count, catalog item or evidence (VC-R02) */
#define VERICULL_E_AMBIGUOUS    (-3) /* ABI-401 sweep only: the lexer cannot classify the buffer
                                        safely (a regex-context `/` inside a template substitution);
                                        every claim is reported unsatisfied */
#define VERICULL_E_LENGTH       (-4) /* a buffer length or element count exceeds its documented cap */
#define VERICULL_E_NOMEM        (-5) /* std::bad_alloc or std::length_error while allocating */
#define VERICULL_E_INTERNAL     (-6) /* any other std::exception (or unknown exception) */

/* Length caps (N3/N4). Every public entry rejects a haystack or query longer than
 * VERICULL_MAX_HAYSTACK_LEN with VERICULL_E_LENGTH before touching the buffer. The cap is far
 * below INT32_MAX, so every byte offset fits the int32_t offset outputs, and it bounds the
 * per-call working set to roughly 9 bytes per haystack byte. */
#define VERICULL_MAX_HAYSTACK_LEN 67108864u /* 64 MiB; must stay <= INT32_MAX */
#define VERICULL_MAX_PATTERNS     65536u
#define VERICULL_MAX_TRIAL_COUNT  100000u   /* ABI 402 repro/stage count cap (matches Python/JS) */

/* Pattern catalog validation (C3): scope 0..3, token_count 0..16777213 (so token_count + 2 is
 * exact in binary32). An item outside these ranges is rejected with VERICULL_E_INVALID. */
#define VERICULL_MAX_PATTERN_SCOPE       3u
#define VERICULL_MAX_PATTERN_TOKEN_COUNT 16777213u

/* ABI 402 sweep output flags */
#define VERICULL_SWEEP_FLAG_LEXER_AMBIGUOUS 0x1u

/* ABI 402 adjudication flags (VericullStageEvidence.flags) */
#define VERICULL_ADJ_FLAG_LEGACY_AGGREGATE_S4 0x1u /* authenticated legacy replay ONLY: an absent
                                                       s3/s4 count falls back to the aggregate
                                                       quorum. Never set this when issuing. */

/* Language grammar hints for lexical classification (0 = polyglot auto-inference) */
#define VERICULL_LANG_AUTO      0u
#define VERICULL_LANG_C         1u
#define VERICULL_LANG_CPP       2u
#define VERICULL_LANG_RUST      3u
#define VERICULL_LANG_GO        4u
#define VERICULL_LANG_TS_JS     5u
#define VERICULL_LANG_VERILOG   6u
#define VERICULL_LANG_TEXT      7u /* records and logs: only a terminated block note is masked.
                                      Selected ONLY through a trusted caller parameter
                                      (`lang_mode` / `lang_hint` of vericull_lex_inspect_ex); a
                                      claim's lang_hint of 7 or more means AUTO. */

/* 3-band zero-LLM router triage actions (VCSF-36 64-tree classifier) */
#define VERICULL_ACTION_CULL        0 /* P(TP) < 0.30: drop unanchored/noise alert immediately */
#define VERICULL_ACTION_QUARANTINE  1 /* 0.30 <= P(TP) < 0.70: non-blocking fuzz/solver/panel queue */
#define VERICULL_ACTION_ESCALATE    2 /* P(TP) >= 0.70: high-confidence defect, block CI merge */

/* Mechanized gate verdict states (VC-R01 .. VC-R04) */
#define VERICULL_VERDICT_CULLED_CLAIM         0 /* VC-R01: zero claims or failed active-code span */
#define VERICULL_VERDICT_QUARANTINED_HOLD     1 /* VC-R03: anchored in active code, guarded/unreproduced */
#define VERICULL_VERDICT_STATIC_INVARIANT     2 /* VC-R01: positive + negative active-span invariant proved */
#define VERICULL_VERDICT_FLAKY_FAULT          3 /* VC-R04: fault observed, Wilson 95% lower < 0.50 or < S4 */
#define VERICULL_VERDICT_DETERMINISTIC_IMPACT 4 /* VC-R04: S4 impact across >=4 runs & Wilson lower >= 0.50 */

typedef struct VericullLexStats {
    uint32_t total_bytes;
    uint32_t code_bytes;
    uint32_t comment_bytes;
    uint32_t literal_bytes;
    uint32_t line_count;
    uint32_t max_brace_depth;
} VericullLexStats;

typedef struct VericullClaim {
    char     needle[64];     /* UTF-8 byte pattern (bytes 0..needle_len-1) */
    uint32_t needle_len;     /* UTF-8 byte length of needle (1..63) */
    uint32_t span_start;     /* Inclusive start byte offset (0 = start of buffer) */
    uint32_t span_end;       /* Exclusive end byte offset (0 = end of buffer) */
    int32_t  must_be_absent; /* 0 = positive active anchor, 1 = negative absence invariant */
    uint32_t lang_hint;      /* Optional hint on claim[0]: 0..6 used only when the trusted mode is AUTO;
                                any other value (including VERICULL_LANG_TEXT) means AUTO */
    uint32_t magic;          /* Must equal VERICULL_NEEDLE_MAGIC (0x56434E44) */
} VericullClaim;

typedef struct VericullGBDTTree {
    int32_t num_nodes;
    int32_t split_indices[VERICULL_MAX_NODES];
    float   split_conditions[VERICULL_MAX_NODES];
    int32_t left_children[VERICULL_MAX_NODES];
    int32_t right_children[VERICULL_MAX_NODES];
    float   base_weights[VERICULL_MAX_NODES];
} VericullGBDTTree;

typedef struct VericullPatternItem {
    uint32_t scope;          /* 0=case_note, 1=team_checklist, 2=control_rule, 3=charter_invariant (0..3) */
    uint32_t cwe_id;         /* Numeric CWE identifier (e.g. 787, 416, 362; 0 if generic) */
    uint32_t token_count;    /* Word count in canonical pattern rule (0..16777213) */
    uint32_t num_tokens;     /* Unique hashes stored in tokens[0..num_tokens-1] (<= 32) */
    uint64_t tokens[32];     /* Lowercased ASCII identifier FNV-1a64 hashes */
} VericullPatternItem;

typedef struct VericullReport {
    uint32_t magic;                                    /* VERICULL_VERDICT_MAGIC (0x56435644) */
    int32_t  verdict_state;                            /* 0..4 */
    int32_t  router_action;                            /* 0..2 */
    int32_t  highest_stage;                            /* -1 (NONE) or 0..4 (S0..S4) */
    int32_t  claims_total;
    int32_t  claims_passed;
    int32_t  failed_claim_index;                       /* -1 if all claims passed */
    int32_t  repro_quorum_met;                         /* 1 iff attempts>=4 && wilson_lower>=0.50 */
    int32_t  matched_offsets[VERICULL_MAX_CLAIMS];     /* First active byte offset per claim (-1 if absent) */
    int32_t  comment_shadow_offsets[VERICULL_MAX_CLAIMS]; /* First inactive offset: a match touching a comment, or for a positive claim a match wholly inside a string/char literal (-1 if none) */
    int32_t  best_pattern_index;                       /* Winning VCPC pattern index (-1 if none) */
    int32_t  best_pattern_overlap;                     /* Identifier token intersection count */
    float    tp_probability;                           /* 64-tree sigmoid score [0, 1]; not a calibrated probability */
    float    wilson_ci95_lower;
    float    wilson_ci95_upper;
    float    top_pattern_score;
    uint64_t sweep_digest;                             /* FNV-1a64 digest of active claim vector */
    uint64_t provenance_seal_hash;                     /* 64-bit VCVD SplitMix64 provenance seal */
} VericullReport;

/* ABI 402 stage evidence. A stage count is used only when its presence flag is 1 and must be 0
 * when its presence flag is 0 (VERICULL_E_INVALID otherwise). Issuance
 * semantics (flags == 0): S4 is certified only when stage_mask bit 4 is set AND s4_passes is
 * present AND the Wilson quorum over (s4_passes, repro_attempts) is met; S3 likewise with
 * s3_passes. An absent count demotes that stage exactly like a failed quorum. */
typedef struct VericullStageEvidence {
    uint32_t repro_passes;         /* 0..VERICULL_MAX_TRIAL_COUNT, <= repro_attempts */
    uint32_t repro_attempts;       /* 0..VERICULL_MAX_TRIAL_COUNT */
    uint32_t s3_passes;            /* <= repro_passes when present */
    uint32_t s4_passes;            /* <= repro_passes, and <= s3_passes when both are present */
    int32_t  has_s3_passes;        /* 0 = absent, 1 = present; anything else is invalid */
    int32_t  has_s4_passes;        /* 0 = absent, 1 = present; anything else is invalid */
    int32_t  has_static_invariant; /* 0 or 1 */
    int32_t  stage_mask;           /* 0..0xFFFF; bits 0..4 are S0..S4 */
    uint32_t flags;                /* 0 (issuance) or VERICULL_ADJ_FLAG_LEGACY_AGGREGATE_S4 */
} VericullStageEvidence;

typedef struct VericullReport402 {
    VericullReport base;           /* same meaning as ABI 401; base.repro_quorum_met is the
                                      effective quorum bound into the seal */
    int32_t  lexer_ambiguous;      /* 1 iff the buffer is lexically ambiguous (no claim satisfied; held, not culled) */
    int32_t  s3_quorum_met;        /* effective S3 quorum after presence rules */
    int32_t  s4_quorum_met;        /* effective S4 quorum after presence rules */
    uint32_t flags;                /* echo of VericullStageEvidence.flags */
} VericullReport402;

/* Highest supported ABI (VERICULL_ABI_VERSION_402). */
uint32_t vericull_abi_version(void);

/* Lexical statistics. `lang_hint` here is a trusted caller selection (VERICULL_LANG_TEXT allowed).
 * Returns 0, VERICULL_E_NULL, VERICULL_E_LENGTH, VERICULL_E_NOMEM or VERICULL_E_INTERNAL. */
int32_t vericull_lex_inspect(
    const uint8_t* haystack,
    uint32_t haystack_len,
    VericullLexStats* out_stats
);

int32_t vericull_lex_inspect_ex(
    const uint8_t* haystack,
    uint32_t haystack_len,
    uint32_t lang_hint,
    VericullLexStats* out_stats
);

/*
 * Sweeps `claims[0..num_claims-1]` (`0 <= num_claims <= VERICULL_MAX_CLAIMS`) over `haystack`.
 * Buffer contract:
 *   - When `num_claims > 0`, `claims` and `out_matched_offsets` MUST be non-NULL and have capacity
 *     for at least `num_claims` elements (`out_comment_shadow_offsets` is optional; if non-NULL,
 *     it MUST also have capacity for at least `num_claims` elements). Only indices `0..num_claims-1`
 *     are written.
 *   - Returns `passed_count` (`0..num_claims`) on success, `-1` on NULL required pointer, or `-2`
 *     on invalid claim descriptor / `num_claims > VERICULL_MAX_CLAIMS`, VERICULL_E_LENGTH when
 *     `haystack_len > VERICULL_MAX_HAYSTACK_LEN`, VERICULL_E_NOMEM / VERICULL_E_INTERNAL on an
 *     internal failure, or VERICULL_E_AMBIGUOUS when the buffer is lexically ambiguous (the
 *     offset and digest outputs are still written, with every claim unsatisfied).
 *   - The grammar comes from `claims[0].lang_hint` only when it is 0..6; any other value
 *     (including VERICULL_LANG_TEXT) selects AUTO. Record mode needs vericull_aho_corasick_sweep_ex.
 *   - A positive claim (`must_be_absent == 0`) anchors only on a match with no comment byte and at
 *     least one byte outside string/char literals. An absence claim (`must_be_absent != 0`) fails
 *     on any match with no comment byte, including one inside a literal.
 */
int32_t vericull_aho_corasick_sweep(
    const uint8_t* haystack,
    uint32_t haystack_len,
    const VericullClaim* claims,
    uint32_t num_claims,
    int32_t* out_matched_offsets,
    int32_t* out_comment_shadow_offsets,
    int32_t* out_failed_index,
    uint64_t* out_sweep_digest
);

/*
 * ABI 402 sweep. `lang_mode` is the trusted caller-selected grammar (0..7; any other value is
 * AUTO). Only when it is AUTO may `claims[0].lang_hint` (0..6) select a source grammar.
 * `out_flags` is required: VERICULL_SWEEP_FLAG_LEXER_AMBIGUOUS is set when the buffer is
 * lexically ambiguous, in which case every claim is unsatisfied regardless of polarity and the
 * return value is the passed count (0). Other returns as vericull_aho_corasick_sweep.
 */
int32_t vericull_aho_corasick_sweep_ex(
    const uint8_t* haystack,
    uint32_t haystack_len,
    uint32_t lang_mode,
    const VericullClaim* claims,
    uint32_t num_claims,
    int32_t* out_matched_offsets,
    int32_t* out_comment_shadow_offsets,
    int32_t* out_failed_index,
    uint64_t* out_sweep_digest,
    uint32_t* out_flags
);

int32_t vericull_gbdt_eval(
    const VericullGBDTTree* trees,
    uint32_t num_trees,
    float base_score_logit,
    const float* features,
    uint32_t num_features,
    float* out_tp_probability,
    int32_t* out_router_action
);

/*
 * Legacy recall (ABI 401 signature). It cannot return a status: on an invalid catalog item,
 * an over-cap length or an internal failure it writes the negative status code into
 * `*out_best_index` (score 0, overlap 0). Use vericull_pattern_recall_ex to receive the status.
 */
void vericull_pattern_recall(
    const uint8_t* query_bytes,
    uint32_t query_len,
    uint32_t query_cwe_id,
    const VericullPatternItem* patterns,
    uint32_t num_patterns,
    float* out_best_score,
    int32_t* out_best_index,
    int32_t* out_best_overlap
);

/*
 * Status-returning recall. Returns VERICULL_OK, VERICULL_E_NULL, VERICULL_E_INVALID (catalog
 * item scope > 3 or token_count > 16777213), VERICULL_E_LENGTH (query_len above
 * VERICULL_MAX_HAYSTACK_LEN or num_patterns above VERICULL_MAX_PATTERNS), VERICULL_E_NOMEM or
 * VERICULL_E_INTERNAL. Outputs are always written (no match = index -1) before scoring.
 */
int32_t vericull_pattern_recall_ex(
    const uint8_t* query_bytes,
    uint32_t query_len,
    uint32_t query_cwe_id,
    const VericullPatternItem* patterns,
    uint32_t num_patterns,
    float* out_best_score,
    int32_t* out_best_index,
    int32_t* out_best_overlap
);

/*
 * ABI 401 adjudication: LEGACY REPLAY ONLY. It has no per-stage counts, so S3/S4 certification
 * uses the aggregate quorum (the "legacy aggregate" semantics of records without
 * `adjudication_semantics`). Never use it to issue a new verdict; use vericull_adjudicate_402.
 * Returns the verdict (0..4) or a negative status (including VERICULL_E_AMBIGUOUS).
 */
int32_t vericull_adjudicate(
    const uint8_t* haystack,
    uint32_t haystack_len,
    const VericullClaim* claims,
    uint32_t num_claims,
    const VericullGBDTTree* trees,
    uint32_t num_trees,
    float base_score_logit,
    const float* features,
    uint32_t num_features,
    const uint8_t* query_bytes,
    uint32_t query_len,
    uint32_t query_cwe_id,
    const VericullPatternItem* patterns,
    uint32_t num_patterns,
    uint32_t repro_passes,
    uint32_t repro_attempts,
    int32_t  has_static_invariant,
    int32_t  stage_mask,
    VericullReport* out_report
);

/*
 * ABI 402 adjudication with issuance semantics ("vericull.stage-evidence.v2"). `lang_mode` is
 * the trusted grammar selection as in vericull_aho_corasick_sweep_ex. A lexically ambiguous
 * buffer is unsupported input: no claim is satisfied, lexer_ambiguous = 1, and issuance HOLDS it
 * (verdict VERICULL_VERDICT_QUARANTINED_HOLD, highest_stage -1); it is never culled. Only the
 * historical replay flag VERICULL_ADJ_FLAG_LEGACY_AGGREGATE_S4 keeps the older cull, and the
 * older rule that S3/S4 need no positive anchor, so authentic legacy records still replay.
 * Every tree of the model is validated in full (all nodes, finite values, no cycle) on entry.
 * Returns the verdict (0..4) or a negative status.
 */
int32_t vericull_adjudicate_402(
    const uint8_t* haystack,
    uint32_t haystack_len,
    uint32_t lang_mode,
    const VericullClaim* claims,
    uint32_t num_claims,
    const VericullGBDTTree* trees,
    uint32_t num_trees,
    float base_score_logit,
    const float* features,
    uint32_t num_features,
    const uint8_t* query_bytes,
    uint32_t query_len,
    uint32_t query_cwe_id,
    const VericullPatternItem* patterns,
    uint32_t num_patterns,
    const VericullStageEvidence* evidence,
    VericullReport402* out_report
);

/*
 * Internal arithmetic and exception-boundary self-test (N3/N4 regression hook). Exercises the
 * remaining-length lookahead helper at the UINT32_MAX boundary and maps thrown std::bad_alloc,
 * std::length_error and std::exception through the export guard. Returns 0 when every check
 * holds, otherwise the 1-based index of the first failing check.
 */
int32_t vericull_selftest_bounds(void);

#ifdef __cplusplus
}
#endif

#endif /* VERICULL_CORE_H */
