// tools/design-schema/platform-schemas-b.ts — dbt and ML schema generators (split from platform-schemas.ts)
// SPEC-015b: dbt schema generation (moved from platform-schemas.ts for SOLID compliance)
// === dbt schema generation — SPEC-015b ===
/**
 * Returns true if the project is a dbt project.
 */
export function isDbtSchema(knowledge) {
    const { stack } = knowledge;
    return stack.some((s) => ['dbt', 'dbt-core', 'dbt-bigquery', 'dbt-snowflake', 'dbt-postgres'].includes(s.toLowerCase()));
}
function buildDbtModel(layer, name, description, columns) {
    const lines = [
        `  - name: ${name}`,
        `    description: "${description}"`,
        '    columns:',
    ];
    for (const col of columns) {
        lines.push(`      - name: ${col}`);
        lines.push(`        tests:`);
        if (col === 'id' || col.endsWith('_id')) {
            lines.push(`          - unique`);
            lines.push(`          - not_null`);
        }
        else {
            lines.push(`          - not_null`);
        }
    }
    void layer;
    return lines;
}
/**
 * Generate dbt schema.yml with staging, intermediate, and marts layers.
 * SPEC-015b criterion: schema compatible with dbt's schema.yml format.
 */
export function generateDbtSchema(entityNames, knowledge) {
    const primaryEntity = entityNames[0] ?? 'entity';
    const entityLower = primaryEntity.toLowerCase();
    const stackInfo = knowledge.stack.join(', ') || 'dbt';
    const lines = [
        `## dbt Schema (${stackInfo})`,
        '',
        '### Layer Architecture',
        '',
        '```',
        'sources (raw)  →  staging (stg_)  →  intermediate (int_)  →  marts (dim_/fct_)',
        '```',
        '',
        '### schema.yml',
        '',
        '```yaml',
        'version: 2',
        '',
        'models:',
    ];
    // Staging layer
    const stagingColumns = ['id', 'created_at', 'updated_at', 'raw_data'];
    const stagingLines = buildDbtModel('staging', `stg_${entityLower}s`, `Staging layer for ${primaryEntity} — minimal transformations, 1:1 with source`, stagingColumns);
    lines.push(...stagingLines);
    lines.push('');
    // Intermediate layer
    const intermediateColumns = ['id', `${entityLower}_key`, 'status', 'amount'];
    const intermediateLines = buildDbtModel('intermediate', `int_${entityLower}s_enriched`, `Intermediate layer — business logic, joins, and derived fields for ${primaryEntity}`, intermediateColumns);
    lines.push(...intermediateLines);
    lines.push('');
    // Marts — dimension
    const dimColumns = ['id', `${entityLower}_name`, 'category', 'is_active'];
    const dimLines = buildDbtModel('marts', `dim_${entityLower}s`, `Dimension table for ${primaryEntity} — slowly changing attributes`, dimColumns);
    lines.push(...dimLines);
    lines.push('');
    // Marts — fact
    const fctColumns = [`${entityLower}_id`, 'event_date', 'metric_value', 'count'];
    const fctLines = buildDbtModel('marts', `fct_${entityLower}_events`, `Fact table for ${primaryEntity} events — additive metrics at grain of event`, fctColumns);
    lines.push(...fctLines);
    lines.push('```', '');
    lines.push('### dbt Quality Checklist', '');
    lines.push('- [ ] All staging models have `unique` + `not_null` tests on primary keys');
    lines.push('- [ ] Intermediate models have `relationship` tests for foreign keys');
    lines.push('- [ ] Fact tables are grain-documented (one row per: event_id + date)');
    lines.push('- [ ] Sources defined in `sources.yml` with `freshness` SLA configured');
    lines.push('- [ ] `dbt test` passes 100% before CI merge');
    lines.push('');
    return lines.join('\n');
}
// === ML schema generation (kept here to balance file sizes) ===
function buildMLSchemaConfig(entityNames) {
    const target = entityNames[0] ?? 'data';
    return {
        datasetSchema: [
            `# Dataset schema for ${target}`,
            'features:',
            '  - name: feature_1',
            '    dtype: float32',
            '    description: Primary feature',
            '  - name: feature_2',
            '    dtype: float32',
            '    description: Secondary feature',
            'label:',
            '  name: target',
            '  dtype: int64',
            '  classes: 2  # adjust to your task',
            'splits:',
            '  train: 0.7',
            '  validation: 0.15',
            '  test: 0.15',
        ],
        modelConfig: [
            `# Model configuration for ${target}`,
            'model:',
            '  architecture: transformer  # or cnn, rnn, mlp',
            '  input_size: 128',
            '  hidden_size: 256',
            '  num_layers: 6',
            '  dropout: 0.1',
            '  output_size: 2',
        ],
        hyperparameters: [
            '# Training hyperparameters',
            'training:',
            '  learning_rate: 1.0e-4',
            '  batch_size: 32',
            '  epochs: 100',
            '  optimizer: adamw',
            '  scheduler: cosine_annealing',
            '  weight_decay: 1.0e-5',
            '  early_stopping_patience: 5',
        ],
        metrics: [
            '# Evaluation metrics and thresholds',
            'metrics:',
            '  accuracy:',
            '    threshold: 0.85',
            '    priority: high',
            '  f1_score:',
            '    threshold: 0.80',
            '    priority: high',
            '  auc_roc:',
            '    threshold: 0.90',
            '    priority: medium',
            '  inference_latency_ms:',
            '    threshold: 100',
            '    priority: medium',
        ],
    };
}
/**
 * Generate ML schema including dataset schema, model config, hyperparameters, and metrics.
 */
export function generateMLSchema(entityNames, knowledge) {
    const config = buildMLSchemaConfig(entityNames);
    const stackInfo = knowledge.stack.join(', ') || 'Python/ML';
    const lines = [`## ML/AI Schema (${stackInfo})`, ''];
    const sections = [
        { title: 'Dataset Schema', content: config.datasetSchema, lang: 'yaml' },
        { title: 'Model Configuration', content: config.modelConfig, lang: 'yaml' },
        { title: 'Training Hyperparameters', content: config.hyperparameters, lang: 'yaml' },
        { title: 'Metrics & Thresholds', content: config.metrics, lang: 'yaml' },
    ];
    for (const section of sections) {
        lines.push(`### ${section.title}`, '');
        lines.push(`\`\`\`${section.lang}`);
        for (const line of section.content) {
            lines.push(line);
        }
        lines.push('```', '');
    }
    lines.push('### ML Quality Gates', '');
    lines.push('- [ ] Data validation tests pass (schema, types, missing values)');
    lines.push('- [ ] Train/val/test split is stratified and reproducible (seed fixed)');
    lines.push('- [ ] Model accuracy meets threshold before deployment');
    lines.push('- [ ] Data drift detection configured (evidently, alibi-detect)');
    lines.push('- [ ] Model versioned in experiment tracker (MLflow, W&B)');
    lines.push('');
    return lines.join('\n');
}
//# sourceMappingURL=platform-schemas-b.js.map