// ============ READ / FETCH OPERATIONS ============
export const fetchSamples = [
  {
    title: "Fetch by Key",
    badge: "GET",
    code: 'from("users") | get("user_102")',
    desc: "Direct key lookup — fastest way to retrieve a specific record.",
    hint: "O(1) lookup time. Returns single record or null if not found.",
  },
  {
    title: "Fetch Multiple Keys",
    badge: "FILTER",
    code: 'from("users") | filter(key in ["user_102", "user_103", "user_104"])',
    desc: "Fetch multiple specific keys using the set membership 'in' operator.",
    hint: "Highly optimized; leverages the in-memory SkipMap index directly.",
  },
  {
    title: "Fetch All Records",
    badge: "FROM",
    code: 'from("users")',
    desc: "Fetch all active records in a stream.",
    hint: "Use with limit() on large streams to prevent client-side memory bloating.",
  },
  {
    title: "Limit Result Count",
    badge: "LIMIT",
    code: 'from("logs") | limit(100)',
    desc: "Cap the maximum number of records evaluated and returned by the stream query.",
    hint: "Highly recommended for active dashboard console views to prevent accidental massive full scans.",
  },
  {
    title: "Filter Items",
    badge: "FILTER",
    code: 'from("orders") | filter(amount > 100)',
    desc: "Filter records where property conditions match.",
    hint: "Supports ==, !=, >, <, >=, <=, in, contains, startsWith, endsWith, between",
  },
  {
    title: "Vector Similarity Filter",
    badge: "VECTOR",
    code: 'from("embeddings") | vector_filter(value, [10, -20, 30], 0.85)',
    desc: "Filter records using native quantized embedding cosine similarity relative to a query vector.",
    hint: "Highly optimized vector calculations compute cosine similarity on-the-fly with zero-allocation.",
  },
  {
    title: "Substring Match (contains)",
    badge: "FILTER",
    code: 'from("logs") | filter(message contains "error")',
    desc: "Filter records where a string field contains a given substring.",
    hint: "Case-sensitive substring match using the native contains operator. More flexible than startsWith for searching inside message bodies.",
  },
  {
    title: "Suffix Match (endsWith)",
    badge: "FILTER",
    code: 'from("files") | filter(name endsWith ".log")',
    desc: "Filter records where a string field ends with a given suffix.",
    hint: "Useful for file extension filtering, domain matching, or any suffix-based pattern.",
  },
  {
    title: "Range Filter (between)",
    badge: "FILTER",
    code: 'from("orders") | filter(amount between [100, 500])',
    desc: "Filter records where a numeric field falls within an inclusive range.",
    hint: "The value must be an array with exactly two elements: [lower, upper]. Both bounds are inclusive.",
  },
  {
    title: "Negation (not)",
    badge: "FILTER",
    code: 'from("users") | filter(not status == "inactive")',
    desc: "Invert any filter expression using the not operator.",
    hint: 'Can be combined with parentheses: filter(not (status == "inactive" or status == "deleted"))',
  },
  {
    title: "Filter by Key Prefix",
    badge: "FILTER",
    code: 'from("users") | filter(key startsWith "user_")',
    desc: "Filter keys by prefix pattern matching.",
    hint: "Extremely fast because keys are sorted chronologically in the index layer.",
  },
  {
    title: "Chain Multiple Filters",
    badge: "FILTER",
    code: 'from("logs") | filter(status == "error") | filter(timestamp > 1700000000)',
    desc: "Apply multiple filter conditions sequentially down the pipeline.",
    hint: "Performance tip: Order matters. Place your most restrictive filters first.",
  },
  {
    title: "Filter with Logical Operators",
    badge: "FILTER",
    code: 'from("orders") | filter(amount > 100 and status == "completed")',
    desc: "Combine complex evaluation conditions with 'and', 'or', and 'not'.",
    hint: "Use parentheses to enforce explicit evaluation order: (a == 1 or b == 2) and c == 3",
  },
  {
    title: "Map Fields",
    badge: "MAP",
    code: 'from("users") | map(name, email, status)',
    desc: "Project only specific fields from each record to reduce payload size.",
    hint: "Reduces network bandwidth usage and accelerates frontend rendering.",
  },
  {
    title: "Distinct by Field",
    badge: "DISTINCT",
    code: 'from("events") | distinct(type)',
    desc: "Remove duplicate records by field value. Retains only the first record for each unique value of the specified field.",
    hint: "Useful for deduplicating time-series data, getting unique categories, or cleaning up repeated sensor readings.",
  },
  {
    title: "Count Items",
    badge: "COUNT",
    code: 'from("users") | count()',
    desc: "Get total number of records matching criteria.",
    hint: "Executes directly against metadata frameworks—much faster than pulling records.",
  },
  {
    title: "Group Items",
    badge: "GROUP",
    code: 'from("orders") | group(status, count(), sum(amount))',
    desc: "Group data by specific fields and compute real-time aggregations.",
    hint: "Supported aggregations: count(), sum(), avg(), min(), max(), first(), last()",
  },
  {
    title: "Sort Items",
    badge: "SORT",
    code: 'from("orders") | sort(timestamp, desc)',
    desc: "Sort records by field in ascending (asc) or descending (desc) order.",
    hint: "Default streaming is chronological; use desc to get newest records first.",
  },
  {
    title: "Paginate Items",
    badge: "PAGE",
    code: 'from("users") | page(2, 50)',
    desc: "Built-in offsetless pagination: page(pageNumber, pageSize).",
    hint: "Page 1 is the base layer. VASTLY superior performance to standard SQL offset limits.",
  },
  {
    title: "Paginate with Cursor",
    badge: "PAGE",
    code: 'from("events") | page(cursor("2026-05-30T11:42:00Z"), 50)',
    desc: "Cursor-based pagination for high-velocity real-time event streams.",
    hint: "Eliminate pagination drift caused by concurrent updates during read states.",
  },
  {
    title: "Enrich Stream Data",
    badge: "ENRICH",
    code: 'from("orders") | enrich("customers", "customer_id")',
    desc: "Perform a left join to enrich the current record stream with data from another stream using a matching join key.",
    hint: "Combines data from primary stream and enriched source stream on matching join keys.",
  },
  {
    title: "Sliding Window",
    badge: "WINDOW",
    code: 'from("logs") | window(10000, average)',
    desc: "Aggregate records over sliding time windows of a specified duration in milliseconds.",
    hint: "Aggregation strategies: count, sum, average.",
  },
  {
    title: "Discover Active Streams",
    badge: "STREAMS",
    code: "streams()",
    desc: "Retrieve the complete list of active stream partitions currently managed by LIVEN.",
    hint: "Useful for discovering stream schemas and allocation details.",
  },
  {
    title: "Real-time Stream Listen",
    badge: "LISTEN",
    code: 'from("orders").listen()',
    desc: "Subscribe to a stream and receive all new records in real-time via WebSocket. Returns historical snapshot first, then streams live records.",
    hint: "Use pipes for filtered subscriptions — only matching records are streamed.",
  },
  {
    title: "Filtered Real-time Listen",
    badge: "LISTEN",
    code: 'from("orders") | filter(amount > 100) .listen()',
    desc: "Subscribe to a filtered stream — only records matching the pipeline are delivered in real-time. The server evaluates pipeline stages on each new record.",
    hint: "Supports any pipeline stage: filter, vector_filter, correlate, sequence, chain, map, enrich.",
  },
  {
    title: "Vector Similarity Listen",
    badge: "LISTEN",
    code: 'from("embeddings") | vector_filter(value, [12, -45, 98], 0.85) .listen()',
    desc: "Subscribe to semantically similar vectors in real-time using cosine similarity filtering on live records.",
    hint: "Combines vector similarity search with live streaming — ideal for real-time semantic monitoring.",
  },
  {
    title: "Execution Analysis (Explain)",
    badge: "EXPLAIN",
    code: 'explain("from(orders) | filter(amount > 100)")',
    desc: "Parse a query and return a cost-annotated execution plan without executing it. Each step shows Big-O cost and estimated record counts.",
    hint: "Use explain to debug query performance, identify expensive operations (like correlate triggering a full scan), and verify your pipeline before running it on production data.",
  },
  {
    title: "Explain an Insert",
    badge: "EXPLAIN",
    code: 'explain("from(users).insert(k1, {name: test})")',
    desc: "Get an execution plan for a write operation, showing the existence check, append, and index update steps.",
    hint: "The plan shows estimated costs for every step: existence_check (O(log n)), append (O(1)), index_update (O(log n)).",
  },
  {
    title: "Explain List Streams",
    badge: "EXPLAIN",
    code: 'explain("streams()")',
    desc: "Analyze the streams() query — confirms it reads from in-memory state with no disk access.",
    hint: "Confirming zero-disk operations helps diagnose whether slow queries are I/O bound or CPU bound.",
  },
  {
    title: "Tail Real-time Stream",
    badge: "TAIL",
    code: 'tail("orders")',
    desc: "Low-level subscription query to tail all incoming events of a stream partition in real-time.",
    hint: "Feeds updates automatically into the Query Console via direct WebSocket subscription.",
  },
  {
    title: "Filter by Timestamp Range",
    badge: "FILTER",
    code: 'from("events") | filter(timestamp > 1700000000000)',
    desc: "Filter records by timestamp range using a time-indexed scan. Uses the per-stream timestamp index for O(log N + K) range lookups instead of a full segment scan.",
    hint: "Now uses the per-stream timestamp index: first query with a time-range filter populates the index; subsequent queries are O(log N). Supports gt, lt, gte, lte, eq, and between operators on the timestamp field.",
  },
  {
    title: "Filter by Timestamp Window",
    badge: "FILTER",
    code: 'from("sensors") | filter(timestamp between [1700000000000, 1700086400000])',
    desc: "Filter records within a timestamp range using the between operator. The server uses the timestamp index for efficient retrieval without a full historical scan.",
    hint: "The timestamp field is in milliseconds since Unix epoch. Combine with limit() for optimal performance on time-bounded queries.",
  },
  {
    title: "System Status",
    badge: "STATUS",
    code: "status()",
    desc: "Retrieve current server metrics: max connections, active connections, and broadcast capacity.",
    hint: "Useful for monitoring connection pool saturation and diagnosing broadcast channel backpressure.",
  },
  {
    title: "Explain Status",
    badge: "EXPLAIN",
    code: 'explain("status()")',
    desc: "Analyze the status() query — confirms it reads entirely from in-memory atomic counters with zero disk I/O.",
    hint: "status() is O(1) and never touches disk. Compare with from(stream) which triggers a full scan.",
  },
  {
    title: "Execution Analysis with Timestamp Index",
    badge: "EXPLAIN",
    code: 'explain("from(events) | filter(timestamp > 1700000000000)")',
    desc: "Verify that a time-range query uses the timestamp index instead of a full segment scan.",
    hint: "The plan will show 'timestamp index scan' when a time-range filter is detected on the timestamp field — this is O(log N) instead of O(N).",
  },
];

// ============ WRITE / INSERT OPERATIONS ============
export const insertSamples = [
  {
    title: "Insert Single Record",
    badge: "INSERT",
    code: 'from("users").insert("user_102", { name: "Alice", email: "alice@example.com" })',
    desc: "Insert a completely unique key-value entry into the data stream.",
    hint: "Strict Integrity: Fails safely with a KeyAlreadyExists error if the key is already indexed.",
  },
  {
    title: "Insert Multiple Records (Bulk Batch)",
    badge: "BATCH",
    code: 'from("users").insert([["user_103", { name: "Bob" }], ["user_104", { name: "Charlie" }]])',
    desc: "Batch insert multiple unique records atomically in a single structural array.",
    hint: "If any key already exists in the SkipMap, the entire batch aborts to preserve integrity.",
  },
  {
    title: "Insert Stream Event (Client-Keyed)",
    badge: "STREAM",
    code: 'from("events").insert("click:cta_btn:1717068000", { userId: "user_102", duration_ms: 12 })',
    desc: "Stream a chronological event using a deterministic composite key created by your application.",
    hint: "Stream-First Architecture: Mandating client-side keys preserves maximum database write-throughput.",
  },
  {
    title: "Insert Vector Embedding",
    badge: "VECTOR",
    code: 'from("embeddings").insert("doc_101", [12, -45, 98, -128, 127])',
    desc: "Insert a native 8-bit quantized vector embedding for semantic search indexing.",
    hint: "Vectors are stored in-memory as efficient i8 contiguous segments and support high-speed similarity filtering.",
  },
  {
    title: "Insert Document with Embedding Field",
    badge: "INSERT",
    code: 'from("documents").insert("doc_102", { text: "Hello LIVEN", embedding: [12, -45, 98] })',
    desc: "Insert structured document records containing semantic text and associated vector embeddings.",
    hint: "Pipeline filtering stages can parse and filter nested properties as well as full payloads.",
  },
];

// ============ OVERRIDE / UPSERT OPERATIONS ============
export const upsertSamples = [
  {
    title: "Upsert Record by Key",
    badge: "UPSERT",
    code: 'from("users").upsert("user_102", { name: "Alice", status: "active", updated: true })',
    desc: "Force-write a key-value record. Overwrites the existing value if the key already exists.",
    hint: "Appends a new version frame to the log file and atomically updates the in-memory SkipMap pointer.",
  },
  {
    title: "Bulk Upsert Records",
    badge: "UPSERT",
    code: 'from("inventory").upsert([["SKU-001", { qty: 150 }], ["SKU-002", { qty: 85 }]])',
    desc: "Perform a high-velocity batch override across multiple key parameters simultaneously.",
    hint: "Superseded historical records remain on disk as dead weight until a log compaction cycle runs.",
  },
];

// ============ UPDATE OPERATIONS ============
export const updateSamples = [
  {
    title: "Update by Key",
    badge: "UPDATE",
    code: 'from("users").update("user_102", { status: "active", lastLogin: now() })',
    desc: "Update specific properties of a record matching an explicit key identifier.",
    hint: "Delta update—appends changes to disk and merges them during read execution.",
  },
  {
    title: "Update Multiple Keys",
    badge: "UPDATE",
    code: 'from("users") | filter(key in ["user_102", "user_103"]) .update({ status: "inactive" })',
    desc: "Select a fixed array of records using filters, then execute a bulk update.",
    hint: "Atomic pointer redirection occurs immediately upon successful log write.",
  },
  {
    title: "Update with Filter Pipeline",
    badge: "UPDATE",
    code: 'from("orders") | filter(status == "pending") .update({ status: "processing" })',
    desc: "Scan a stream pipeline and apply mutations across all matched criteria.",
    hint: "Pipelines build the target collection safely; the terminal dot-method applies changes.",
  },
  {
    title: "Update with Computed Values",
    badge: "UPDATE",
    code: 'from("products") | filter(price < 10) .update({ price: price * 1.1, updatedAt: now() })',
    desc: "Update property values dynamically by referencing current field parameters.",
    hint: "Supports native mathematical operations, mutations, and internal function counters.",
  },
];

// ============ DELETE / REMOVE OPERATIONS ============
export const deleteSamples = [
  {
    title: "Delete by Key",
    badge: "DELETE",
    code: 'from("users").delete("user_102")',
    desc: "Delete a specific key completely out of the active retrieval pathway.",
    hint: "Soft deletion writes a tombstone flag to the log. Reclaimed completely on compaction.",
  },
  {
    title: "Delete with Filter Pipeline",
    badge: "DELETE",
    code: 'from("users") | filter(status == "inactive") .delete()',
    desc: "Perform a sweeping conditional deletion of records matching filter pipelines.",
    hint: "Pipelines isolate targeted arrays safely, while terminal dot-execution alters state.",
  },
  {
    title: "Empty All Stream Records",
    badge: "EMPTY",
    code: 'from("logs").empty()',
    desc: "Completely clear and truncate all records inside an active stream partition.",
    hint: "Highly efficient log truncation. Wipes entries but preserves the stream allocation profile.",
  },
  {
    title: "Drop Entire Stream Schema",
    badge: "DROP",
    code: 'drop("old_metrics_2025")',
    desc: "Completely drop a structural stream partition directory from the host system file architecture.",
    hint: "Administrative Action: Instantly unlinks all `.liven` segments and completely removes data maps from memory.",
  },
];

// ============ RELATIONSHIP OPERATIONS ============
export const relationshipSamples = [
  {
    title: "Correlate Streams by Time Window",
    badge: "CORRELATE",
    code: 'from("transactions") | correlate("logins", "user_id", within: 60000)',
    desc: "Join two streams on a shared key within a time window. Retains and enriches records that have matching events in the correlated stream.",
    hint: "Place restrictive filters before correlate to reduce the record set before the windowed join executes. The correlate stage now pre-fetches source records into a HashMap for O(1) lookups.",
  },
  {
    title: "Correlate for Fraud Detection",
    badge: "CORRELATE",
    code: 'from("transactions") | filter(amount > 1000) | correlate("logins", "user_id", within: 300000)',
    desc: "Detect high-value transactions with no associated login event in the preceding time window — a fraud signal.",
    hint: "Filter before correlate reduces cost. The within value is in milliseconds: 300000 = 5 minutes.",
  },
  {
    title: "Detect Event Sequences",
    badge: "SEQUENCE",
    code: 'from("telemetry") | sequence(event == "cpu_spike", then: event == "memory_leak", within: 30000)',
    desc: "Detect ordered event patterns within a time boundary using a finite state machine. Returns the record that completes each sequence.",
    hint: "Sequence resets when the time window expires. Maximum 10 steps per sequence pattern.",
  },
  {
    title: "Detect Repeated Failed Logins",
    badge: "SEQUENCE",
    code: 'from("auth") | sequence(action == "login_fail", then: action == "login_fail", then: action == "login_fail", within: 60000)',
    desc: "Detect three consecutive login failures within 60 seconds — a brute force signal.",
    hint: "Each completed sequence emits the final matching record. The FSM resets after each match.",
  },
  {
    title: "Chain Stream Relationships",
    badge: "CHAIN",
    code: 'from("prompts") | chain("responses", "prompt_id")',
    desc: "Follow a causal relationship from one stream to another by remapping the join key at each hop.",
    hint: "Chain is a left join — records without a match in the target stream are retained with their original value.",
  },
  {
    title: "Multi-Hop Chain Traversal",
    badge: "CHAIN",
    code: 'from("prompts") | chain("responses", "prompt_id") | chain("memory", "response_id")',
    desc: "Traverse a causal chain across multiple streams. Each hop follows the relationship one level deeper.",
    hint: "Use for AI memory linking, transaction lineage, and multi-step event tracing.",
  },
  {
    title: "Transaction Lineage",
    badge: "CHAIN",
    code: 'from("orders") | chain("shipments", "order_id") | chain("deliveries", "shipment_id")',
    desc: "Follow an order through its full fulfillment chain across three streams in a single query.",
    hint: "Each chain stage remaps the join key to the next relationship in the chain.",
  },
];
