// tools/design-schema/nosql-category-schemas.ts — Schema generators for NoSQL categories (SPEC-059)
// Covers: Cache (B.3), Search (C.3), Time-Series (D.2), Vector (F.3)
// === Cache Schema (B.3) ===
export function isCacheSchema(knowledge) {
    return knowledge.cacheEngine !== undefined && knowledge.cacheEngine !== null;
}
export function generateCacheSchema(entityNames, knowledge) {
    const engine = knowledge.cacheEngine ?? 'redis';
    const prefix = entityNames[0]?.toLowerCase() ?? 'app';
    const lines = [
        `## Cache Schema Design — ${engine.toUpperCase()}`,
        '',
        '### Key Naming Conventions',
        `- Pattern: \`${prefix}:{entity}:{id}\``,
        ...entityNames.map((e) => `- \`${prefix}:${e.toLowerCase()}:{id}\` → single record`),
        ...entityNames.map((e) => `- \`${prefix}:${e.toLowerCase()}:list\` → collection cache`),
        '',
        '### TTL Policies',
        '| Key Pattern | TTL | Rationale |',
        '|-------------|-----|-----------|',
        ...entityNames.map((e) => `| \`${prefix}:${e.toLowerCase()}:*\` | 3600s | Standard entity cache |`),
        `| \`${prefix}:session:*\` | 86400s | User session data |`,
        '',
        '### Data Structure Selection',
        '| Use Case | Structure | Command |',
        '|----------|-----------|---------|',
        '| Single record | STRING (JSON) | GET/SET |',
        '| Entity fields | HASH | HGET/HSET |',
        '| Sorted lists | SORTED SET | ZADD/ZRANGE |',
        '| Event log | STREAM | XADD/XREAD |',
        '| Unique items | SET | SADD/SMEMBERS |',
        '',
        '### Eviction Strategy',
        `- Recommended: \`allkeys-lru\` (evict least recently used when memory full)`,
        '- Max memory: set via `maxmemory` directive',
        '',
        '### Serialization Format',
        '- JSON for complex objects (human-readable, cross-language)',
        '- MessagePack for high-throughput (compact binary, faster)',
    ];
    return lines.join('\n');
}
// === Search Schema (C.3) ===
export function isSearchSchema(knowledge) {
    return knowledge.searchEngine !== undefined && knowledge.searchEngine !== null;
}
export function generateSearchSchema(entityNames, knowledge) {
    const engine = knowledge.searchEngine ?? 'elasticsearch';
    const isElastic = engine === 'elasticsearch' || engine === 'opensearch';
    const lines = [`## Search Engine Schema Design — ${engine}`, '', '### Index Mappings'];
    for (const entity of entityNames) {
        const idx = entity.toLowerCase();
        if (isElastic) {
            lines.push(`\n#### Index: \`${idx}\``, '```json', '{', `  "mappings": {`, `    "properties": {`, `      "id": { "type": "keyword" },`, `      "name": { "type": "text", "analyzer": "standard" },`, `      "description": { "type": "text", "analyzer": "standard" },`, `      "status": { "type": "keyword" },`, `      "created_at": { "type": "date" },`, `      "updated_at": { "type": "date" }`, `    }`, `  }`, '}', '```');
        }
        else {
            lines.push(`\n#### Index: \`${idx}\``, '- Searchable: `name`, `description`', '- Filterable: `id`, `status`, `created_at`', '- Sortable: `created_at`, `updated_at`');
        }
    }
    lines.push('', '### Search Settings', '- Synonyms: define domain-specific synonym groups', '- Stop words: use default language stop words', '- Ranking rules: relevance → date → exact match', '', '### Reindex Strategy', '- Zero-downtime: create new index → bulk index → alias swap', '- Incremental: use change streams / CDC for real-time sync', '- Full rebuild: schedule during low-traffic windows');
    return lines.join('\n');
}
// === Time-Series Schema (D.2) ===
export function isTimeseriesSchema(knowledge) {
    return knowledge.timeseriesDb !== undefined && knowledge.timeseriesDb !== null;
}
export function generateTimeseriesSchema(entityNames, knowledge) {
    const engine = knowledge.timeseriesDb ?? 'influxdb';
    const isInflux = engine === 'influxdb';
    const isTimescale = engine === 'timescaledb';
    const lines = [`## Time-Series Schema Design — ${engine}`, ''];
    if (isInflux) {
        lines.push('### Measurements');
        for (const entity of entityNames) {
            lines.push(`\n#### Measurement: \`${entity.toLowerCase()}_metrics\``, '| Column | Type | Role |', '|--------|------|------|', '| time | timestamp | Primary index |', `| ${entity.toLowerCase()}_id | tag | Indexed dimension |`, '| region | tag | Indexed dimension |', '| value | field (float) | Metric value |', '| count | field (integer) | Event count |');
        }
    }
    else if (isTimescale) {
        lines.push('### Hypertables');
        for (const entity of entityNames) {
            const tbl = entity.toLowerCase();
            lines.push(`\n#### Hypertable: \`${tbl}_events\``, '```sql', `CREATE TABLE ${tbl}_events (`, `  time TIMESTAMPTZ NOT NULL,`, `  ${tbl}_id UUID NOT NULL,`, `  metric_name TEXT NOT NULL,`, `  value DOUBLE PRECISION,`, `  metadata JSONB`, ');', `SELECT create_hypertable('${tbl}_events', 'time');`, '```');
        }
    }
    else {
        lines.push('### Tables');
        for (const entity of entityNames) {
            lines.push(`\n#### Table: \`${entity.toLowerCase()}_events\``, '- Timestamp column: `time` (designated timestamp)', `- Symbol columns: \`${entity.toLowerCase()}_id\`, \`region\``, '- Value columns: `value` (double), `count` (long)');
        }
    }
    lines.push('', '### Retention Policies', '| Data Tier | Retention | Resolution |', '|-----------|-----------|------------|', '| Hot | 7 days | Raw (1s) |', '| Warm | 30 days | 1-minute aggregates |', '| Cold | 1 year | 1-hour aggregates |', '', '### Continuous Aggregates', '- 1-minute rollups: avg, min, max, count per metric', '- 1-hour rollups: avg, p50, p95, p99 per metric', '- Daily summaries: total count, avg value per entity', '', '### Downsampling Strategy', '- Automatic: scheduled jobs move raw → aggregated after retention window', '- Manual: run backfill queries for historical data migration');
    return lines.join('\n');
}
// === Vector Schema (F.3) ===
export function isVectorSchema(knowledge) {
    return ((knowledge.vectorDb !== undefined && knowledge.vectorDb !== null) ||
        knowledge.hasVectorExtension === true);
}
export function generateVectorSchema(entityNames, knowledge) {
    const engine = knowledge.vectorDb ?? (knowledge.hasVectorExtension ? 'pgvector' : 'pinecone');
    const isPgvector = engine === 'pgvector';
    const lines = [`## Vector Database Schema Design — ${engine}`, ''];
    if (isPgvector) {
        lines.push('### pgvector Extension Tables');
        for (const entity of entityNames) {
            const tbl = entity.toLowerCase();
            lines.push(`\n#### Table: \`${tbl}_embeddings\``, '```sql', `CREATE TABLE ${tbl}_embeddings (`, `  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),`, `  ${tbl}_id UUID NOT NULL REFERENCES ${tbl}s(id),`, `  embedding vector(1536),  -- OpenAI ada-002 dimensions`, `  metadata JSONB,`, `  created_at TIMESTAMPTZ DEFAULT now()`, ');', `CREATE INDEX ON ${tbl}_embeddings USING hnsw (embedding vector_cosine_ops);`, '```');
        }
    }
    else {
        lines.push('### Collections');
        for (const entity of entityNames) {
            const col = entity.toLowerCase();
            lines.push(`\n#### Collection: \`${col}_vectors\``, '```json', '{', `  "name": "${col}_vectors",`, `  "dimension": 1536,`, `  "metric": "cosine",`, `  "metadata_schema": {`, `    "${col}_id": "string",`, `    "category": "string",`, `    "created_at": "datetime"`, `  }`, '}', '```');
        }
    }
    lines.push('', '### Index Configuration', '| Parameter | Value | Rationale |', '|-----------|-------|-----------|', '| Index type | HNSW | Best recall/speed tradeoff |', '| ef_construction | 200 | Higher = better recall, slower build |', '| M | 16 | Connections per layer |', '| ef_search | 100 | Query-time accuracy |', '', '### Metadata Fields', '- `source_id`: reference to source record', '- `chunk_index`: position in chunked document', '- `model`: embedding model identifier', '- `version`: embedding model version for re-embedding tracking', '', '### Embedding Model Reference', '| Model | Dimensions | Use Case |', '|-------|------------|----------|', '| text-embedding-ada-002 | 1536 | General purpose (OpenAI) |', '| text-embedding-3-small | 1536 | Cost-effective (OpenAI) |', '| all-MiniLM-L6-v2 | 384 | Open-source, fast |', '| voyage-large-2 | 1024 | Code & technical docs |');
    return lines.join('\n');
}
//# sourceMappingURL=nosql-category-schemas.js.map