// tools/create-spec/platform-spec-adapter.ts
// SPEC-015a: Adapts FICHA-TECNICA.md technical sheet to bot/smart-contract/ml/iot spec types
// Criterion 18: create_spec adapts technical sheet to platform type
// === Platform detection helpers ===
function isSmartContractSpec(spec, knowledge) {
    const category = knowledge?.projectCategory;
    const framework = knowledge?.framework?.toLowerCase() ?? '';
    const stack = (knowledge?.stack ?? []).map((s) => s.toLowerCase());
    if (category === 'smart-contract') {
        return true;
    }
    if (['hardhat', 'foundry', 'anchor', 'move'].includes(framework)) {
        return true;
    }
    if (stack.some((s) => ['solidity', 'hardhat', 'foundry'].includes(s))) {
        return true;
    }
    return spec.tags.some((t) => ['smart-contract', 'solidity', 'blockchain', 'defi', 'nft'].includes(t.toLowerCase()));
}
function isBotSpec(spec, knowledge) {
    const category = knowledge?.projectCategory;
    const stack = (knowledge?.stack ?? []).map((s) => s.toLowerCase());
    if (category === 'bot') {
        return true;
    }
    if (stack.some((s) => ['discord.js', 'telegraf', 'grammy', '@slack/bolt'].includes(s))) {
        return true;
    }
    return spec.tags.some((t) => ['bot', 'discord', 'telegram', 'slack', 'whatsapp'].includes(t.toLowerCase()));
}
function isMLSpec(spec, knowledge) {
    const category = knowledge?.projectCategory;
    const stack = (knowledge?.stack ?? []).map((s) => s.toLowerCase());
    if (category === 'ml') {
        return true;
    }
    const mlIndicators = [
        'pytorch',
        'tensorflow',
        'scikit-learn',
        'sklearn',
        'langchain',
        'transformers',
    ];
    if (stack.some((s) => mlIndicators.some((ind) => s.includes(ind)))) {
        return true;
    }
    return spec.tags.some((t) => ['ml', 'ai', 'machine-learning', 'llm', 'rag', 'neural-network'].includes(t.toLowerCase()));
}
function isIoTSpec(spec, knowledge) {
    const category = knowledge?.projectCategory;
    const stack = (knowledge?.stack ?? []).map((s) => s.toLowerCase());
    if (category === 'iot') {
        return true;
    }
    if (stack.some((s) => ['platformio', 'arduino', 'zephyr'].includes(s))) {
        return true;
    }
    return spec.tags.some((t) => ['iot', 'embedded', 'arduino', 'esp32', 'raspberry-pi', 'firmware'].includes(t.toLowerCase()));
}
// === Section builders ===
function buildSmartContractSection() {
    return [
        '## Smart Contract Architecture',
        '',
        '**Contract structure:**',
        '- `contracts/` — Solidity source files',
        '- `scripts/` — Deployment scripts',
        '- `test/` — Contract tests (Hardhat/Foundry)',
        '',
        '**Key concerns:**',
        '- Storage layout: minimize SSTORE calls (pack variables into slots)',
        '- Access control: define roles upfront (ADMIN_ROLE, MINTER_ROLE, etc.)',
        '- Upgrade strategy: UUPS / Transparent Proxy / Beacon (if upgradeable)',
        '- Events: emit on every state change for off-chain indexing',
        '',
        '**Security requirements:**',
        '- [ ] Reentrancy guard (`nonReentrant`) on all value-transferring functions',
        '- [ ] Slither + Mythril scan must pass before mainnet deployment',
        '- [ ] Gas optimization: no unbounded loops',
        '- [ ] Audit scheduled before production launch',
        '',
    ];
}
function buildBotSection(framework) {
    const fwLabel = framework || 'discord.js / Telegraf / Slack Bolt';
    return [
        '## Bot Architecture',
        '',
        `**Framework:** ${fwLabel}`,
        '',
        '**Command handler structure:**',
        '- Command registration (slash commands / message commands)',
        '- Middleware chain: auth → rate-limit → validate → handle',
        '- Event listeners: message, interaction, reaction, member join/leave',
        '',
        '**Key concerns:**',
        '- Rate limiting: respect platform API limits per route',
        '- Cooldowns: per-user cooldown for expensive commands',
        '- Error handling: graceful degradation, never crash the process',
        '- State management: Redis or in-memory for ephemeral state',
        '',
        '**Bot deployment:**',
        '- [ ] Bot token stored securely (env var, not code)',
        '- [ ] Intents declared (only request what you need)',
        '- [ ] Reconnect logic implemented (exponential backoff)',
        '- [ ] Logging structured (pino/winston, level=info in production)',
        '',
    ];
}
function buildMLSection(stack) {
    const isLangChain = stack.some((s) => s.includes('langchain'));
    const lines = [
        '## ML/AI Architecture',
        '',
        '**Project structure:**',
        '- `data/` — Raw and processed datasets (DVC tracked)',
        '- `models/` — Saved model artifacts',
        '- `notebooks/` — Exploratory analysis (never used in production)',
        '- `src/` — Production training and inference code',
        '',
        '**ML workflow:**',
        '1. Data ingestion → validation (Great Expectations)',
        '2. Feature engineering → preprocessing pipeline',
        '3. Model training → experiment tracking (MLflow/W&B)',
        '4. Evaluation → accuracy/F1/latency thresholds',
        '5. Model registry → staging → production promotion',
        '',
    ];
    if (isLangChain) {
        lines.push('**LLM-specific concerns:**', '- Prompt versioning (store prompts in version control)', '- Token budget management (track cost per request)', '- Hallucination mitigation (retrieval grounding, self-critique)', '- Evaluation: Ragas / LangSmith for RAG quality metrics', '');
    }
    lines.push('**Quality gates:**', '- [ ] Dataset schema validated before training', '- [ ] Experiment tracked with hyperparameters and metrics', '- [ ] Model accuracy threshold met on test split', '- [ ] Drift detection configured for production', '');
    return lines;
}
function buildIoTSection() {
    return [
        '## IoT/Embedded Architecture',
        '',
        '**Hardware targets:**',
        '- (List target MCU/board: ESP32, Arduino Mega, STM32, Raspberry Pi, etc.)',
        '',
        '**Firmware structure:**',
        '- `src/main.*` — Entry point and hardware init',
        '- `src/sensors/` — Sensor drivers',
        '- `src/comms/` — Network/protocol handlers (MQTT, CoAP, HTTP)',
        '- `src/storage/` — Local data buffering',
        '',
        '**Communication:**',
        '- Protocol: MQTT / CoAP / HTTP (specify)',
        '- Broker: (Mosquitto / AWS IoT / Azure IoT Hub)',
        '- QoS: define per message type (fire-and-forget vs guaranteed delivery)',
        '',
        '**Power management:**',
        '- Sleep modes: deep sleep between readings',
        '- Wake frequency: (define polling interval)',
        '- Battery threshold alerts: warn at 20%, critical at 10%',
        '',
        '**OTA updates:**',
        '- [ ] Dual partition OTA (A/B) configured',
        '- [ ] Checksum validation before applying firmware',
        '- [ ] Rollback on boot failure',
        '- [ ] Minimum battery level required for OTA',
        '',
    ];
}
// === Public API ===
/**
 * Get platform-specific FICHA-TECNICA sections for the spec.
 * Returns empty array if no specialty platform detected.
 */
export function getPlatformSpecSection(spec, knowledge) {
    const stack = (knowledge?.stack ?? []).map((s) => s.toLowerCase());
    const framework = knowledge?.framework ?? '';
    if (isSmartContractSpec(spec, knowledge)) {
        return buildSmartContractSection();
    }
    if (isBotSpec(spec, knowledge)) {
        return buildBotSection(framework);
    }
    if (isMLSpec(spec, knowledge)) {
        return buildMLSection(stack);
    }
    if (isIoTSpec(spec, knowledge)) {
        return buildIoTSection();
    }
    return [];
}
//# sourceMappingURL=platform-spec-adapter.js.map