// tools/design-schema/advanced-db-schemas.ts — Schema generators for advanced DB categories (SPEC-059)
// Covers: Graph (E.2), Wide-Column (G.2), Cloud-Managed (H.4)
// === Graph Schema (E.2) ===
export function isGraphSchema(knowledge) {
    return knowledge.graphDb !== undefined && knowledge.graphDb !== null;
}
export function generateGraphSchema(entityNames, knowledge) {
    const engine = knowledge.graphDb ?? 'neo4j';
    const isCypher = engine === 'neo4j' || engine === 'neptune';
    const isArango = engine === 'arangodb';
    const lines = [`## Graph Database Schema Design — ${engine}`, ''];
    if (isCypher) {
        lines.push('### Node Labels & Properties');
        for (const entity of entityNames) {
            lines.push(`\n#### Label: \`:${entity}\``, '```cypher', `CREATE CONSTRAINT ${entity.toLowerCase()}_id_unique`, `  FOR (n:${entity}) REQUIRE n.id IS UNIQUE;`, '', `CREATE (n:${entity} {`, `  id: randomUUID(),`, `  name: "",`, `  created_at: datetime(),`, `  updated_at: datetime()`, '});', '```');
        }
        lines.push('', '### Relationship Types');
        if (entityNames.length >= 2) {
            const [a, b] = entityNames;
            lines.push('```cypher', 
            /* v8 ignore next 2 -- noUncheckedIndexedAccess fallback */
            `CREATE (a:${a ?? 'A'})-[:RELATES_TO {since: datetime()}]->(b:${b ?? 'B'});`, `CREATE (a:${a ?? 'A'})-[:BELONGS_TO]->(b:${b ?? 'B'});`, '```');
        }
        lines.push('', '### Traversal Patterns (Cypher)', '```cypher', `// Find all related entities`, 
        /* v8 ignore next 4 -- noUncheckedIndexedAccess fallback */
        `MATCH (a:${entityNames[0] ?? 'Entity'})-[r]->(b)`, `RETURN a, type(r), b LIMIT 100;`, '', '// Shortest path', `MATCH p = shortestPath((a:${entityNames[0] ?? 'Entity'})-[*..10]-(b:${entityNames[0] ?? 'Entity'}))`, 'RETURN p;', '```');
    }
    else if (isArango) {
        lines.push('### Document Collections');
        for (const entity of entityNames) {
            lines.push(`- \`${entity.toLowerCase()}\` — vertex collection`);
        }
        lines.push('', '### Edge Collections');
        lines.push('- `relations` — generic edge collection');
        lines.push('', '### Traversal Patterns (AQL)');
        lines.push('```aql', `FOR v, e, p IN 1..3 OUTBOUND @startId GRAPH 'myGraph'`, '  RETURN { vertex: v, edge: e, path: p }', '```');
    }
    else {
        lines.push('### Nodes');
        for (const entity of entityNames) {
            lines.push(`- \`${entity}\`: id (string), name (string), created_at (datetime)`);
        }
        lines.push('', '### Edges', '- `relates_to`: from (string), to (string), weight (float)');
    }
    lines.push('', '### Constraints', '| Type | Target | Description |', '|------|--------|-------------|', ...entityNames.map((e) => `| Uniqueness | ${e}.id | Prevent duplicate identifiers |`), ...entityNames.map((e) => `| Existence | ${e}.name | Required property |`));
    return lines.join('\n');
}
// === Wide-Column Schema (G.2) ===
export function isWideColumnSchema(knowledge) {
    const wideColumnEngines = ['cassandra', 'scylladb', 'hbase', 'clickhouse'];
    return wideColumnEngines.includes(knowledge.database);
}
export function generateWideColumnSchema(entityNames, knowledge) {
    const engine = knowledge.database;
    const isClickHouse = engine === 'clickhouse';
    const lines = [`## Wide-Column Schema Design — ${engine}`, ''];
    if (isClickHouse) {
        lines.push('### ClickHouse Tables');
        for (const entity of entityNames) {
            const tbl = entity.toLowerCase();
            lines.push(`\n#### Table: \`${tbl}_events\``, '```sql', `CREATE TABLE ${tbl}_events (`, '  event_date Date,', '  event_time DateTime,', `  ${tbl}_id UUID,`, '  event_type LowCardinality(String),', '  payload String,', '  value Float64', `) ENGINE = MergeTree()`, `PARTITION BY toYYYYMM(event_date)`, `ORDER BY (event_date, ${tbl}_id, event_time)`, 'TTL event_date + INTERVAL 90 DAY;', '```');
        }
        lines.push('', '### Engine Selection Guide', '| Engine | Use Case |', '|--------|----------|', '| MergeTree | Default — sorted, partitioned |', '| ReplacingMergeTree | Upserts / dedup by version |', '| AggregatingMergeTree | Pre-aggregated rollups |', '| CollapsingMergeTree | Mutable state with +1/-1 rows |');
    }
    else {
        const keyspace = 'app_keyspace';
        lines.push('### Keyspace', '```cql', `CREATE KEYSPACE IF NOT EXISTS ${keyspace}`, "  WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};", '```', '', '### Tables');
        for (const entity of entityNames) {
            const tbl = entity.toLowerCase();
            lines.push(`\n#### Table: \`${keyspace}.${tbl}\``, '```cql', `CREATE TABLE ${keyspace}.${tbl} (`, `  ${tbl}_id UUID,`, '  created_at TIMESTAMP,', '  name TEXT,', '  data TEXT,', `  PRIMARY KEY (${tbl}_id, created_at)`, ') WITH CLUSTERING ORDER BY (created_at DESC)', "  AND compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_size': 1, 'compaction_window_unit': 'DAYS'}", '  AND default_time_to_live = 7776000;', '```');
        }
        lines.push('', '### Partition & Clustering Strategy', '- Partition key: entity ID (even distribution)', '- Clustering column: timestamp DESC (latest first)', '- Target partition size: < 100MB', '', '### Compaction Strategy', '| Strategy | Use Case |', '|----------|----------|', '| STCS | Write-heavy, general purpose |', '| LCS | Read-heavy, consistent latency |', '| TWCS | Time-series, TTL-heavy data |');
    }
    return lines.join('\n');
}
// === Cloud-Managed Schema (H.4) ===
export function isCloudManagedSchema(knowledge) {
    const cloudEngines = ['dynamodb', 'cosmosdb'];
    return cloudEngines.includes(knowledge.database);
}
export function generateCloudManagedSchema(entityNames, knowledge) {
    const engine = knowledge.database;
    if (engine === 'dynamodb') {
        return generateDynamoDbSchema(entityNames);
    }
    return generateCosmosDbSchema(entityNames);
}
function generateDynamoDbSchema(entityNames) {
    const lines = ['## DynamoDB Schema Design', ''];
    for (const entity of entityNames) {
        const tbl = entity;
        lines.push(`### Table: \`${tbl}\``, '```json', '{', `  "TableName": "${tbl}",`, `  "KeySchema": [`, `    { "AttributeName": "PK", "KeyType": "HASH" },`, `    { "AttributeName": "SK", "KeyType": "RANGE" }`, `  ],`, `  "AttributeDefinitions": [`, `    { "AttributeName": "PK", "AttributeType": "S" },`, `    { "AttributeName": "SK", "AttributeType": "S" },`, `    { "AttributeName": "GSI1PK", "AttributeType": "S" },`, `    { "AttributeName": "GSI1SK", "AttributeType": "S" }`, `  ],`, `  "BillingMode": "PAY_PER_REQUEST",`, `  "GlobalSecondaryIndexes": [`, `    {`, `      "IndexName": "GSI1",`, `      "KeySchema": [`, `        { "AttributeName": "GSI1PK", "KeyType": "HASH" },`, `        { "AttributeName": "GSI1SK", "KeyType": "RANGE" }`, `      ],`, `      "Projection": { "ProjectionType": "ALL" }`, `    }`, `  ],`, `  "TimeToLiveSpecification": {`, `    "AttributeName": "ttl",`, `    "Enabled": true`, `  }`, '}', '```', '');
    }
    lines.push('### Access Patterns', '| Pattern | PK | SK | Index |', '|---------|----|----|-------|', ...entityNames.map((e) => `| Get ${e} by ID | \`${e.toUpperCase()}#{id}\` | \`METADATA\` | Table |`), ...entityNames.map((e) => `| List ${e} by date | \`${e.toUpperCase()}\` | \`DATE#{iso}\` | Table |`), '', '### Capacity Mode', '- **On-Demand**: recommended for unpredictable workloads', '- **Provisioned**: use for steady-state with auto-scaling', '', '### TTL', '- Attribute: `ttl` (Unix epoch seconds)', '- DynamoDB automatically deletes expired items');
    return lines.join('\n');
}
function generateCosmosDbSchema(entityNames) {
    const lines = ['## CosmosDB Schema Design', ''];
    for (const entity of entityNames) {
        lines.push(`### Container: \`${entity.toLowerCase()}\``, '```json', '{', `  "id": "${entity.toLowerCase()}",`, `  "partitionKey": { "paths": ["/${entity.toLowerCase()}Id"], "kind": "Hash" },`, `  "indexingPolicy": {`, `    "automatic": true,`, `    "indexingMode": "consistent",`, `    "includedPaths": [{ "path": "/*" }],`, `    "excludedPaths": [{ "path": "/metadata/*" }],`, `    "compositeIndexes": [[`, `      { "path": "/createdAt", "order": "descending" },`, `      { "path": "/status", "order": "ascending" }`, `    ]]`, `  },`, `  "defaultTtl": -1`, '}', '```', '');
    }
    lines.push('### Consistency Level', '| Level | Latency | Consistency | Use Case |', '|-------|---------|-------------|----------|', '| Strong | High | Full | Financial transactions |', '| Bounded Staleness | Medium | Bounded | Analytics dashboards |', '| Session | Low | Per-session | Default — user interactions |', '| Eventual | Lowest | Eventual | Logging, telemetry |', '', '### Partition Key Strategy', '- Choose high-cardinality field (e.g., userId, tenantId)', '- Avoid hot partitions: distribute writes evenly', '- Target partition size: < 20GB logical partition');
    return lines.join('\n');
}
//# sourceMappingURL=advanced-db-schemas.js.map