"""
Type definitions, enums, and constants for xwquery.
This module defines all shared types and enums used across the xwquery library,
following the same pattern as xwnode/defs.py.
Company: eXonware.com
Author: eXonware Backend Team
Email: connect@exonware.com
Version: 0.0.1.8
Generation Date: October 26, 2025
"""

from enum import Enum, Flag, auto
# ============================================================================
# QUERY EXECUTION MODES
# ============================================================================

class QueryMode(Enum):
    """Query execution modes."""
    IMMEDIATE = auto()      # Execute immediately
    LAZY = auto()           # Lazy evaluation
    STREAMING = auto()      # Stream results
    BATCH = auto()          # Batch processing
    PARALLEL = auto()       # Parallel execution
    AUTO = auto()           # Automatic mode selection


class QueryOptimization(Enum):
    """Query optimization strategies."""
    NONE = auto()           # No optimization
    BASIC = auto()          # Basic optimizations
    AGGRESSIVE = auto()     # Aggressive optimizations
    ADAPTIVE = auto()       # Adaptive based on data


class ParserMode(Enum):
    """Parser modes."""
    STRICT = auto()         # Strict parsing
    TOLERANT = auto()       # Tolerant parsing
    PERMISSIVE = auto()     # Very permissive


class ConversionMode(Enum):
    """Conversion modes for parsers and generators."""
    STRICT = auto()         # Strict conversion
    FLEXIBLE = auto()       # Flexible conversion
    LENIENT = auto()        # Very lenient conversion


class QueryTrait(Flag):
    """Query traits/flags."""
    STRUCTURED = auto()     # Structured query (SQL, etc.)
    UNSTRUCTURED = auto()   # Unstructured query (text search)
    ANALYTICAL = auto()     # Analytical query (aggregations)
    TRANSACTIONAL = auto()  # Transactional query (CRUD)
    BATCH = auto()          # Batch processing
    STREAMING = auto()      # Streaming processing
    GRAPH = auto()          # Graph query
    TIME_SERIES = auto()    # Time series query
    TEMPORAL = auto()       # Temporal query
    DOCUMENT = auto()       # Document query
    SEARCH = auto()         # Search query
# ============================================================================
# FORMAT TYPES
# ============================================================================

class FormatType(Enum):
    """Supported query format types."""
    # Core formats
    XWQUERY = "xwquery"
    SQL = "sql"
    # Graph query languages
    GRAPHQL = "graphql"
    CYPHER = "cypher"
    GREMLIN = "gremlin"
    SPARQL = "sparql"
    GQL = "gql"
    # Document databases
    MONGODB = "mongodb"
    MQL = "mql"
    COUCHDB = "couchdb"
    CQL = "cql"
    # Search engines
    ELASTICSEARCH = "elasticsearch"
    EQL = "eql"
    # Time series
    PROMQL = "promql"
    FLUX = "flux"
    LOGQL = "logql"
    # Data query languages
    JMESPATH = "jmespath"
    JQ = "jq"
    JSONIQ = "jsoniq"
    XPATH = "xpath"
    XQUERY = "xquery"
    # Scripting / programming (xwsyntax grammars, same quality as SQL)
    JAVASCRIPT = "javascript"
    TYPESCRIPT = "typescript"
    PYTHON = "python"
    GO = "go"
    RUBY = "ruby"
    PHP = "php"
    LUA = "lua"
    BASH = "bash"
    POWERSHELL = "powershell"
    GROOVY = "groovy"
    KOTLIN = "kotlin"
    SWIFT = "swift"
    DART = "dart"
    ELIXIR = "elixir"
    SCALA = "scala"
    JULIA = "julia"
    HCL = "hcl"
    SOLIDITY = "solidity"
    RUST = "rust"
    WASM = "wasm"
    WEBASSEMBLY = "wasm"
    # Others
    DATALOG = "datalog"
    LINQ = "linq"
    N1QL = "n1ql"
    PARTIQL = "partiql"
    HIVEQL = "hiveql"
    HQL = "hql"
    PIG = "pig"
    KQL = "kql"
    REQL = "reql"
    RQL = "rql"
# ============================================================================
# OPERATION TYPES
# ============================================================================

class OperationType(Enum):
    """
    Operation category classification.
    Used to group the 195 operations by their primary purpose.
    """
    CORE = auto()           # SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, TRUNCATE, UPSERT, EXPLAIN
    FILTERING = auto()      # WHERE, FILTER, BETWEEN, LIKE, IN, HAS, EXISTS, NOT_IN, IS_NULL, etc.
    AGGREGATION = auto()    # GROUP BY, HAVING, SUM, AVG, COUNT, MIN, MAX, DISTINCT, STDDEV, etc.
    ORDERING = auto()       # ORDER BY, LIMIT, OFFSET
    JOINING = auto()        # JOIN, UNION, WITH, OPTIONAL
    GRAPH = auto()          # MATCH, PATH, OUT, IN_TRAVERSE, RETURN, REPEAT, PAGE_RANK, etc.
    PROJECTION = auto()     # PROJECT, EXTEND, CONSTRUCT
    SEARCH = auto()         # TERM, RANGE
    DATA_OPS = auto()       # LOAD, STORE, MERGE, ALTER, DESCRIBE, IMPORT, EXPORT, COPY, BULK_WRITE
    CONTROL_FLOW = auto()   # FOREACH, LET, FOR
    WINDOW = auto()         # WINDOW, AGGREGATE
    ARRAY = auto()          # SLICING, INDEXING, UNWIND, FLATTEN, PUSH, POP, etc.
    ADVANCED = auto()       # ASK, SUBSCRIBE, MUTATION, PIPE, OPTIONS, VALUES, PIVOT, etc.
    CONDITIONAL = auto()    # CASE, COALESCE, NULLIF, IF_EXPR, SWITCH
    STRING = auto()         # CONCAT, SUBSTRING, UPPER, LOWER, TRIM, REPLACE_STR, etc.
    MATH = auto()           # ABS, CEIL, FLOOR, ROUND, POWER, SQRT, MOD, LOG, etc.
    DATE_TIME = auto()      # NOW, DATE_ADD, DATE_DIFF, EXTRACT_DATE, DATE_FORMAT, etc.
    TYPE_OPS = auto()       # CAST, TYPEOF, TRY_CAST, TO_STRING, TO_NUMBER, etc.


class ExecutionStatus(Enum):
    """Execution status for operations."""
    PENDING = auto()        # Not yet started
    VALIDATING = auto()     # Validating action
    EXECUTING = auto()      # Currently executing
    COMPLETED = auto()      # Successfully completed
    FAILED = auto()         # Execution failed
    CANCELLED = auto()      # Execution cancelled


class OperationCapability(Flag):
    """
    Operation capability flags.
    Defines what capabilities an operation requires to execute.
    """
    NONE = 0
    # Node type requirements
    REQUIRES_LINEAR = auto()
    REQUIRES_TREE = auto()
    REQUIRES_GRAPH = auto()
    REQUIRES_MATRIX = auto()
    # Trait requirements
    REQUIRES_ORDERED = auto()
    REQUIRES_INDEXED = auto()
    REQUIRES_HIERARCHICAL = auto()
    REQUIRES_WEIGHTED = auto()
    REQUIRES_SPATIAL = auto()
    # Special requirements
    REQUIRES_MUTABLE = auto()
    REQUIRES_TRANSACTIONAL = auto()
# ============================================================================
# OPERATION LISTS
# ============================================================================
# Core CRUD operations (9)
CORE_OPERATIONS = [
    "SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP",
    "TRUNCATE", "UPSERT", "EXPLAIN"
]
# Filtering operations (21)
FILTER_OPERATIONS = [
    "WHERE", "FILTER", "BETWEEN", "LIKE", "IN", "HAS", "TERM", "RANGE", "VALUES", "OPTIONAL",
    "EXISTS", "NOT_IN", "IS_NULL", "CONTAINS", "STARTS_WITH", "ENDS_WITH",
    "REGEX", "FUZZY", "IS_MISSING", "ANY_MATCH", "ALL_MATCH"
]
# Aggregation operations (18)
AGGREGATION_OPERATIONS = [
    "SUM", "COUNT", "AVG", "MIN", "MAX", "GROUP", "HAVING", "DISTINCT", "SUMMARIZE",
    "COLLECT", "REDUCE", "STDDEV", "VARIANCE", "MEDIAN", "PERCENTILE",
    "FIRST_VALUE", "LAST_VALUE", "GROUP_CONCAT"
]
# Graph operations (40)
GRAPH_OPERATIONS = [
    "MATCH", "PATH", "OUT", "IN_TRAVERSE", "RETURN",
    "ALL_PATHS", "ALL_SHORTEST_PATHS", "ALL_SIMPLE_PATHS",
    "BOTH", "BOTHE", "BOTHV", "INE", "INV", "OUTE", "OUTV",
    "CLONE", "CONNECTED_COMPONENTS", "CYCLE_DETECTION",
    "CREATE_EDGE", "DELETE_EDGE", "DETACH_DELETE", "UPDATE_EDGE",
    "DEGREE", "EXPAND", "EXTRACT_PATH", "NEIGHBORS",
    "PATH_LENGTH", "PROPERTIES", "SET", "SHORTEST_PATH",
    "SIMPLE_PATH", "SUBGRAPH", "TRAVERSAL", "VARIABLE_PATH",
    "REPEAT", "COALESCE_STEP", "CHOOSE", "ADD_VERTEX", "DROP_VERTEX", "PAGE_RANK"
]
# Ordering operations (4)
ORDERING_OPERATIONS = [
    "ORDER", "BY", "LIMIT", "OFFSET"
]
# Projection operations (2)
PROJECTION_OPERATIONS = [
    "PROJECT", "EXTEND"
]
# Advanced operations (26)
ADVANCED_OPERATIONS = [
    "JOIN", "INCLUDE", "UNION", "MINUS", "WITH", "WINDOW", "PIPE", "LET", "FOR", "FOREACH",
    "ASK", "SUBSCRIBE", "SUBSCRIPTION", "MUTATION", "OPTIONS", "CONSTRUCT", "DESCRIBE",
    "AGGREGATE", "INTERSECT", "SUBQUERY", "PIVOT", "UNPIVOT",
    "ROW_NUMBER", "RANK", "DENSE_RANK", "RECURSIVE_CTE"
]
# Array operations (12)
ARRAY_OPERATIONS = [
    "SLICING", "INDEXING",
    "UNWIND", "FLATTEN", "ARRAY_LENGTH", "ARRAY_CONTAINS",
    "ARRAY_SORT", "ARRAY_REVERSE", "ARRAY_CONCAT", "ARRAY_DISTINCT",
    "PUSH", "POP"
]
# Data operations (8)
DATA_OPERATIONS = [
    "LOAD", "STORE", "MERGE", "FILE_SOURCE",
    "IMPORT", "EXPORT", "COPY", "BULK_WRITE"
]
# Conditional operations (5)
CONDITIONAL_OPERATIONS = [
    "CASE", "COALESCE", "NULLIF", "IF_EXPR", "SWITCH"
]
# String operations (15)
STRING_OPERATIONS = [
    "CONCAT", "SUBSTRING", "UPPER", "LOWER", "TRIM", "REPLACE_STR", "SPLIT",
    "LENGTH", "LPAD", "RPAD", "REVERSE_STR", "POSITION", "REPEAT_STR",
    "REGEX_EXTRACT", "REGEX_REPLACE"
]
# Math operations (14)
MATH_OPERATIONS = [
    "ABS", "CEIL", "FLOOR", "ROUND", "POWER", "SQRT", "MOD",
    "LOG", "EXP", "SIGN", "RANDOM", "GREATEST", "LEAST", "TRUNC"
]
# Date/Time operations (10)
DATETIME_OPERATIONS = [
    "NOW", "DATE_ADD", "DATE_DIFF", "EXTRACT_DATE", "DATE_FORMAT",
    "DATE_PARSE", "DATE_TRUNC", "INTERVAL", "UNIX_TIMESTAMP", "FROM_UNIXTIME"
]
# Type operations (9)
TYPE_OPERATIONS = [
    "CAST", "TYPEOF", "TRY_CAST", "TO_STRING", "TO_NUMBER",
    "TO_BOOLEAN", "TO_DATE", "IS_NUMBER", "IS_STRING"
]
# All operations combined (195)
ALL_OPERATIONS = (
    CORE_OPERATIONS +
    FILTER_OPERATIONS +
    AGGREGATION_OPERATIONS +
    GRAPH_OPERATIONS +
    ORDERING_OPERATIONS +
    PROJECTION_OPERATIONS +
    ADVANCED_OPERATIONS +
    ARRAY_OPERATIONS +
    DATA_OPERATIONS +
    CONDITIONAL_OPERATIONS +
    STRING_OPERATIONS +
    MATH_OPERATIONS +
    DATETIME_OPERATIONS +
    TYPE_OPERATIONS
)
# Operation categories mapping
OPERATION_CATEGORIES: dict[str, list[str]] = {
    "core": CORE_OPERATIONS,
    "filtering": FILTER_OPERATIONS,
    "aggregation": AGGREGATION_OPERATIONS,
    "graph": GRAPH_OPERATIONS,
    "ordering": ORDERING_OPERATIONS,
    "projection": PROJECTION_OPERATIONS,
    "advanced": ADVANCED_OPERATIONS,
    "array": ARRAY_OPERATIONS,
    "data": DATA_OPERATIONS,
    "conditional": CONDITIONAL_OPERATIONS,
    "string": STRING_OPERATIONS,
    "math": MATH_OPERATIONS,
    "datetime": DATETIME_OPERATIONS,
    "type": TYPE_OPERATIONS,
}
__all__ = [
    # Enums
    'QueryMode',
    'QueryOptimization',
    'ParserMode',
    'FormatType',
    'OperationType',
    'ExecutionStatus',
    'OperationCapability',
    # Operation lists
    'CORE_OPERATIONS',
    'FILTER_OPERATIONS',
    'AGGREGATION_OPERATIONS',
    'GRAPH_OPERATIONS',
    'ORDERING_OPERATIONS',
    'PROJECTION_OPERATIONS',
    'ADVANCED_OPERATIONS',
    'ARRAY_OPERATIONS',
    'DATA_OPERATIONS',
    'CONDITIONAL_OPERATIONS',
    'STRING_OPERATIONS',
    'MATH_OPERATIONS',
    'DATETIME_OPERATIONS',
    'TYPE_OPERATIONS',
    'ALL_OPERATIONS',
    'OPERATION_CATEGORIES',
]
