# SPDX-License-Identifier: MIT
# Copyright © 2025 Bijan Mousavi

"""bijux_rag – standalone RAG toolkit.

The package keeps the ingestion path pure (clean → chunk → embed) while exposing typed boundaries for
storage, config parsing, and CLI execution. Functional helpers (Result/Option, Reader/State/Writer),
streaming combinators, retries, and idempotent IO plans are all dependency-lite and deterministic so
pipelines stay reproducible.

Core namespaces:
- `bijux_rag.fp`: functional toolkit and error primitives.
- `bijux_rag.rag`: domain models and pipeline stages (clean/chunk/embed/dedup + config-driven builders).
- `bijux_rag.domain`/`bijux_rag.infra`: capabilities, async effects, logging, retries, storage adapters.
- `bijux_rag.boundaries`: CLI + Pydantic/serde edges for moving data across processes.
"""

from __future__ import annotations

from typing_extensions import assert_never

from .boundaries.adapters.exception_bridge import (
    UnexpectedFailure,
    result_map_try,
    try_result,
    unexpected_fail,
    v_map_try,
    v_try,
)
from .boundaries.app_config import AppConfig
from .boundaries.shells.rag_api_shell import FSReader, write_chunks_jsonl

# Domain value types – immutable, hashable where needed
from .core.rag_types import (
    Chunk,
    ChunkWithoutEmbedding,
    CleanDoc,
    RagEnv,
    RawDoc,
    TextNode,
    TreeDoc,
)
from .core.rules_dsl import (
    abstract_min_len,
    any_doc,
    category_startswith,
    none_doc,
    parse_rule,
    rule_all,
    rule_and,
    rule_not,
    rule_or,
    title_contains,
)
from .core.rules_lint import SafeVisitor, assert_rule_is_safe_expr
from .core.rules_pred import (
    DEFAULT_RULES,
    All,
    AnyOf,
    Eq,
    LenGt,
    Not,
    Pred,
    RulesConfig,
    StartsWith,
    eval_pred,
)
from .core.structural_dedup import DedupIterator, structural_dedup_lazy

# Functional composition helpers (Modules 02–03)
from .fp import (
    FakeTime,
    Reader,
    StageInstrumentation,
    State,
    Writer,
    ask,
    asks,
    censor,
    compose,
    ffilter,
    flatmap,
    flow,
    fmap,
    get,
    identity,
    instrument_stage,
    listen,
    local,
    modify,
    pipe,
    probe,
    producer_pipeline,
    put,
    run_state,
    run_writer,
    tee,
    tell,
    tell_many,
    toggle_logging,
    toggle_metrics,
    toggle_validation,
    transpose_option_result,
    transpose_result_option,
    wr_and_then,
    wr_map,
    wr_pure,
)
from .policies.breakers import (
    BreakInfo,
    circuit_breaker_count_emit,
    circuit_breaker_count_truncate,
    circuit_breaker_pred_emit,
    circuit_breaker_pred_truncate,
    circuit_breaker_rate_emit,
    circuit_breaker_rate_truncate,
    short_circuit_on_err_emit,
    short_circuit_on_err_truncate,
)
from .policies.memo import DiskCache, content_hash_key, lru_cache_custom, memoize_keyed
from .policies.reports import (
    ErrGroup,
    ErrReport,
    fold_error_counts,
    fold_error_report,
    report_to_jsonable,
)
from .policies.resources import auto_close, managed_stream, nested_managed, with_resource_stream
from .policies.retries import (
    RetryCtx,
    RetryDecision,
    exp_policy,
    fixed_policy,
    is_retriable_errinfo,
    restore_input_order,
    retry_map_iter,
)
from .rag.clean_cfg import DEFAULT_CLEAN_CONFIG, CleanConfig, make_cleaner
from .rag.config import (
    DocsReader,
    RagBoundaryDeps,
    RagConfig,
    RagCoreDeps,
    boundary_rag_config,
    get_deps,
    make_gen_rag_fn,
    make_rag_fn,
)
from .rag.core import (
    _trace_iter,
    full_rag_api,
    full_rag_api_docs,
    full_rag_api_path,
    gen_bounded_chunks,
    gen_chunk_doc,
    gen_chunk_spans,
    gen_grouped_chunks,
    gen_overlapping_chunks,
    gen_stream_deduped,
    gen_stream_embedded,
    iter_chunks_from_cleaned,
    iter_rag,
    iter_rag_core,
    safe_rag_pipeline,
    sliding_windows,
    stream_chunks,
)

# Pure pipeline stages – the building blocks
from .rag.stages import (
    chunk_doc,
    clean_doc,
    embed_chunk,
    iter_chunk_doc,
    iter_chunk_spans,
    iter_overlapping_chunks_text,
    structural_dedup_chunks,
)
from .rag.types import DebugConfig, DocRule, Observations, RagTaps, RagTraceV3, TraceLens

# Modules 02–09 public API layer (end-of-Bijux RAG)
from .result import (
    NONE,
    Err,
    ErrInfo,
    NoneVal,
    Ok,
    Option,
    Result,
    Some,
    bind_option,
    bind_result,
    filter_err,
    filter_ok,
    is_err,
    is_none,
    is_ok,
    is_some,
    make_errinfo,
    map_err,
    map_option,
    map_result,
    map_result_iter,
    option_from_nullable,
    option_to_nullable,
    partition_results,
    recover,
    result_and_then,
    result_map,
    to_option,
    unwrap_or,
    unwrap_or_else,
)
from .streaming import (
    Source,
    Transform,
    as_source,
    compose2_transforms,
    compose_transforms,
    ensure_contiguous,
    fence_k,
    fork2_lockstep,
    make_call_gate,
    make_chain,
    make_counter,
    make_merge,
    make_peek,
    make_rate_limit,
    make_roundrobin,
    make_sampler_bernoulli,
    make_sampler_periodic,
    make_sampler_stable,
    make_tap,
    make_throttle,
    make_timestamp,
    multicast,
    source_to_transform,
    tap_prefix,
    throttle,
    trace_iter,
)
from .tree import (
    assert_acyclic,
    flatten,
    flatten_via_fold,
    fold_count_length_maxdepth,
    fold_tree,
    fold_tree_buffered,
    fold_tree_no_path,
    iter_flatten,
    iter_flatten_buffered,
    linear_accumulate,
    linear_reduce,
    max_depth,
    recursive_flatten,
    scan_count_length_maxdepth,
    scan_tree,
)

__all__ = [
    "assert_never",
    # Types
    "RawDoc",
    "CleanDoc",
    "ChunkWithoutEmbedding",
    "Chunk",
    "RagEnv",
    "TextNode",
    "TreeDoc",
    # Pure stages
    "clean_doc",
    "chunk_doc",
    "iter_chunk_spans",
    "iter_chunk_doc",
    "iter_overlapping_chunks_text",
    "embed_chunk",
    "structural_dedup_chunks",
    "DedupIterator",
    "structural_dedup_lazy",
    # Functional composition
    "identity",
    "compose",
    "flow",
    "producer_pipeline",
    "pipe",
    "fmap",
    "ffilter",
    "flatmap",
    "tee",
    "probe",
    "StageInstrumentation",
    "instrument_stage",
    "FakeTime",
    # Result/Option + structured errors (Bijux RAG; includes legacy aliases)
    "Ok",
    "Err",
    "Result",
    "ErrInfo",
    "make_errinfo",
    "is_ok",
    "is_err",
    "map_result",
    "map_err",
    "bind_result",
    "recover",
    "unwrap_or",
    "to_option",
    "Option",
    "Some",
    "NoneVal",
    "NONE",
    "is_some",
    "is_none",
    "map_option",
    "bind_option",
    "unwrap_or_else",
    "option_from_nullable",
    "option_to_nullable",
    "map_result_iter",
    "filter_ok",
    "filter_err",
    "partition_results",
    "result_map",
    "result_and_then",
    # Tree traversal + folds (Bijux RAG)
    "assert_acyclic",
    "flatten",
    "recursive_flatten",
    "iter_flatten",
    "iter_flatten_buffered",
    "flatten_via_fold",
    "max_depth",
    "fold_tree",
    "fold_tree_no_path",
    "fold_tree_buffered",
    "scan_tree",
    "linear_reduce",
    "linear_accumulate",
    "fold_count_length_maxdepth",
    "scan_count_length_maxdepth",
    # Memoization (Bijux RAG)
    "lru_cache_custom",
    "memoize_keyed",
    "DiskCache",
    "content_hash_key",
    # Result stream combinators (Bijux RAG)
    "try_map_iter",
    "par_try_map_iter",
    "tap_ok",
    "tap_err",
    "recover_iter",
    "recover_result_iter",
    "split_results_to_sinks",
    "split_results_to_sinks_guarded",
    # Result stream aggregation (Bijux RAG)
    "ResultsBoth",
    "fold_results_fail_fast",
    "fold_results_collect_errs",
    "fold_results_collect_errs_capped",
    "fold_until_error_rate",
    "all_ok_fail_fast",
    "collect_both",
    # Breakers (Bijux RAG)
    "BreakInfo",
    "short_circuit_on_err_emit",
    "short_circuit_on_err_truncate",
    "circuit_breaker_rate_emit",
    "circuit_breaker_rate_truncate",
    "circuit_breaker_count_emit",
    "circuit_breaker_count_truncate",
    "circuit_breaker_pred_emit",
    "circuit_breaker_pred_truncate",
    # Resource safety (Bijux RAG)
    "with_resource_stream",
    "managed_stream",
    "nested_managed",
    "auto_close",
    # Retries (Bijux RAG)
    "RetryCtx",
    "RetryDecision",
    "retry_map_iter",
    "fixed_policy",
    "exp_policy",
    "is_retriable_errinfo",
    "restore_input_order",
    # Error reporting (Bijux RAG)
    "ErrGroup",
    "ErrReport",
    "fold_error_counts",
    "fold_error_report",
    "report_to_jsonable",
    # Rules (Modules 02–03)
    "DocRule",
    "Pred",
    "Eq",
    "LenGt",
    "StartsWith",
    "All",
    "AnyOf",
    "Not",
    "RulesConfig",
    "DEFAULT_RULES",
    "eval_pred",
    "any_doc",
    "none_doc",
    "category_startswith",
    "title_contains",
    "abstract_min_len",
    "rule_and",
    "rule_or",
    "rule_not",
    "rule_all",
    "parse_rule",
    "SafeVisitor",
    "assert_rule_is_safe_expr",
    # Config + API (Modules 02–03)
    "CleanConfig",
    "DEFAULT_CLEAN_CONFIG",
    "make_cleaner",
    "RagTaps",
    "DebugConfig",
    "Observations",
    "TraceLens",
    "RagTraceV3",
    "RagConfig",
    "RagCoreDeps",
    "DocsReader",
    "RagBoundaryDeps",
    "get_deps",
    "make_rag_fn",
    "make_gen_rag_fn",
    "boundary_rag_config",
    "_trace_iter",
    "gen_chunk_doc",
    "gen_chunk_spans",
    "gen_overlapping_chunks",
    "iter_rag",
    "iter_rag_core",
    "stream_chunks",
    "gen_stream_embedded",
    "gen_stream_deduped",
    "sliding_windows",
    "gen_grouped_chunks",
    "gen_bounded_chunks",
    "safe_rag_pipeline",
    "multicast",
    "throttle",
    "iter_chunks_from_cleaned",
    "full_rag_api",
    "full_rag_api_docs",
    "full_rag_api_path",
    "FSReader",
    "write_chunks_jsonl",
    "AppConfig",
    # Bijux RAG: monads, layering, configurable pipelines, boundary exception bridge
    "Reader",
    "State",
    "Writer",
    "ask",
    "asks",
    "local",
    "get",
    "put",
    "modify",
    "run_state",
    "tell",
    "tell_many",
    "listen",
    "censor",
    "run_writer",
    "wr_pure",
    "wr_map",
    "wr_and_then",
    "transpose_result_option",
    "transpose_option_result",
    "toggle_validation",
    "toggle_logging",
    "toggle_metrics",
    "try_result",
    "result_map_try",
    "v_try",
    "v_map_try",
    "UnexpectedFailure",
    "unexpected_fail",
    # Bijux RAG: generic streaming helpers
    "Source",
    "Transform",
    "trace_iter",
    "fence_k",
    "compose2_transforms",
    "compose_transforms",
    "source_to_transform",
    "tap_prefix",
    "make_chain",
    "make_roundrobin",
    "make_merge",
    "fork2_lockstep",
    "make_throttle",
    "make_rate_limit",
    "make_timestamp",
    "make_call_gate",
    "make_tap",
    "make_counter",
    "make_sampler_bernoulli",
    "make_sampler_periodic",
    "make_sampler_stable",
    "make_peek",
    "ensure_contiguous",
    "as_source",
]

__version__ = "0.1.0"
