// engine/test-generators/platform-test-templates.ts
// SPEC-015a: Test scaffold generators for Smart Contracts and ML projects
// Criteria 12: Smart contract tests (Hardhat/Foundry, fuzzing, invariant)
// Criteria 13: ML tests (data validation, accuracy thresholds, drift detection)
import { buildAnchorTestFile, buildMLRobustnessTestFile } from './platform-test-templates-b.js';
import { buildMLTestContent } from './platform-test-templates-ml.js';
// === Smart contract detection ===
/**
 * Returns true when the project is a smart contract project.
 */
export function isSmartContractProject(knowledge) {
    const { projectCategory, framework, stack } = knowledge;
    if (projectCategory === 'smart-contract') {
        return true;
    }
    if (framework !== null && ['hardhat', 'foundry', 'anchor', 'move'].includes(framework)) {
        return true;
    }
    return stack.some((s) => ['solidity', 'hardhat', 'foundry', 'anchor'].includes(s.toLowerCase()));
}
/**
 * Returns true when the project is an ML/AI project.
 */
export function isMLProject(knowledge) {
    const { projectCategory, stack } = knowledge;
    if (projectCategory === 'ml') {
        return true;
    }
    const mlIndicators = [
        'pytorch',
        'tensorflow',
        'scikit-learn',
        'sklearn',
        'langchain',
        'transformers',
    ];
    return stack.some((s) => mlIndicators.some((ind) => s.toLowerCase().includes(ind)));
}
// === Hardhat test scaffold ===
function buildHardhatTestContent(specTitle) {
    return [
        '// Hardhat test scaffold',
        `// Spec: ${specTitle}`,
        '',
        'import { expect } from "chai";',
        'import { ethers } from "hardhat";',
        'import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";',
        '',
        'describe("Contract tests", () => {',
        '  async function deployFixture() {',
        '    const [owner, otherAccount] = await ethers.getSigners();',
        '    const Contract = await ethers.getContractFactory("MyContract");',
        '    const contract = await Contract.deploy();',
        '    return { contract, owner, otherAccount };',
        '  }',
        '',
        '  it("should deploy successfully", async () => {',
        '    const { contract } = await loadFixture(deployFixture);',
        '    expect(await contract.getAddress()).to.be.properAddress;',
        '  });',
        '',
        '  it("should revert on unauthorized call", async () => {',
        '    const { contract, otherAccount } = await loadFixture(deployFixture);',
        '    await expect(contract.connect(otherAccount).adminFunction())',
        '      .to.be.revertedWithCustomError(contract, "OwnableUnauthorizedAccount");',
        '  });',
        '',
        '  it("should emit event on state change", async () => {',
        '    const { contract, owner } = await loadFixture(deployFixture);',
        '    await expect(contract.stateChangingFunction())',
        '      .to.emit(contract, "StateChanged")',
        '      .withArgs(owner.address);',
        '  });',
        '',
        '  // Reentrancy guard test',
        '  it("should block reentrancy attack", async () => {',
        '    const { contract } = await loadFixture(deployFixture);',
        '    const Attacker = await ethers.getContractFactory("ReentrancyAttacker");',
        '    const attacker = await Attacker.deploy(await contract.getAddress());',
        '    await expect(attacker.attack()).to.be.reverted;',
        '  });',
        '});',
        '',
        '// Fuzzing test (Hardhat Property Testing)',
        'describe("Fuzz tests", () => {',
        '  it("amount never exceeds total supply (fuzz)", async () => {',
        '    // Run with: npx hardhat test --grep "fuzz"',
        '    for (let i = 0; i < 100; i++) {',
        '      const randomAmount = BigInt(Math.floor(Math.random() * 1e18));',
        '      // expect(operation(randomAmount)).to.satisfy invariant',
        '      expect(randomAmount).to.be.greaterThanOrEqual(0n);',
        '    }',
        '  });',
        '});',
    ].join('\n');
}
// === Foundry test scaffold ===
function buildFoundryTestContent(specTitle) {
    return [
        '// Foundry (Forge) test scaffold',
        `// Spec: ${specTitle}`,
        '',
        '// SPDX-License-Identifier: MIT',
        'pragma solidity ^0.8.24;',
        '',
        'import "forge-std/Test.sol";',
        'import "../src/MyContract.sol";',
        '',
        'contract MyContractTest is Test {',
        '    MyContract internal contract_;',
        '    address internal owner = makeAddr("owner");',
        '    address internal attacker = makeAddr("attacker");',
        '',
        '    function setUp() public {',
        '        vm.prank(owner);',
        '        contract_ = new MyContract();',
        '    }',
        '',
        '    function test_DeploySuccess() public {',
        '        assertTrue(address(contract_) != address(0));',
        '    }',
        '',
        '    function test_RevertUnauthorized() public {',
        '        vm.expectRevert();',
        '        vm.prank(attacker);',
        '        contract_.adminFunction();',
        '    }',
        '',
        '    // Foundry fuzzing: property-based tests',
        '    function testFuzz_AmountBounds(uint256 amount) public {',
        '        vm.assume(amount > 0 && amount <= 1e24);',
        '        // invariant: operation with valid amount should succeed',
        '        // contract_.deposit{value: amount}();',
        '        assertTrue(amount > 0);',
        '    }',
        '',
        '    // Foundry invariant test',
        '    function invariant_TotalSupplyMatchesBalances() public {',
        '        // Invariant: sum of all balances == totalSupply',
        '        // assertEq(contract_.totalSupply(), sumAllBalances());',
        '        assertTrue(true); // implement invariant check',
        '    }',
        '}',
    ].join('\n');
}
// === Test definitions ===
/**
 * Generate test definitions for smart contract tests.
 */
export function generateSmartContractTestDefs(title, testDir) {
    return [
        {
            name: `${title} — contract unit tests`,
            type: 'unit',
            file: `${testDir}/contracts/`,
            description: 'Test contract deployment, state changes, and error conditions',
            priority: 'critical',
            automatable: true,
        },
        {
            name: `${title} — reentrancy attack test`,
            type: 'unit',
            file: `${testDir}/contracts/security/`,
            description: 'Verify reentrancy guard blocks attack vector',
            priority: 'critical',
            automatable: true,
        },
        {
            name: `${title} — fuzz/property tests`,
            type: 'unit',
            file: `${testDir}/contracts/fuzz/`,
            description: 'Property-based fuzz tests for arithmetic invariants',
            priority: 'high',
            automatable: true,
        },
        {
            name: `${title} — invariant tests`,
            type: 'integration',
            file: `${testDir}/contracts/invariants/`,
            description: 'Stateful invariant tests (Foundry invariant testing)',
            priority: 'high',
            automatable: true,
        },
    ];
}
/**
 * Generate test definitions for ML tests.
 */
export function generateMLTestDefs(title, testDir) {
    return [
        {
            name: `${title} — data validation`,
            type: 'unit',
            file: `${testDir}/ml/`,
            description: 'Validate dataset schema, types, distributions, and missing values',
            priority: 'critical',
            automatable: true,
        },
        {
            name: `${title} — model accuracy threshold`,
            type: 'unit',
            file: `${testDir}/ml/`,
            description: 'Assert model meets accuracy/F1/latency thresholds',
            priority: 'critical',
            automatable: true,
        },
        {
            name: `${title} — data drift detection`,
            type: 'integration',
            file: `${testDir}/ml/drift/`,
            description: 'KS-test based drift detection on feature and prediction distributions',
            priority: 'high',
            automatable: true,
        },
    ];
}
// === Test file builders ===
/**
 * Build smart contract test files for Hardhat, Foundry, or Anchor.
 * SPEC-015b: Anchor scaffold delegated to platform-test-templates-b.ts
 */
export function buildSmartContractTestFiles(title, slug, testDir, framework, autoGenerate) {
    if (framework === 'foundry') {
        return [
            {
                path: `${testDir}/contracts/${slug}.t.sol`,
                framework: 'foundry',
                content: buildFoundryTestContent(title),
                ready: autoGenerate,
            },
        ];
    }
    if (framework === 'anchor') {
        // SPEC-015b: Anchor (Solana) test scaffold — delegated to separate module
        return [buildAnchorTestFile(title, slug, testDir, autoGenerate)];
    }
    // Default: Hardhat (also covers when framework is null)
    return [
        {
            path: `${testDir}/contracts/${slug}.test.ts`,
            framework: 'hardhat',
            content: buildHardhatTestContent(title),
            ready: autoGenerate,
        },
    ];
}
/**
 * Build ML test files using pytest scaffolds.
 * SPEC-015b: Adds robustness + reproducibility test file.
 */
export function buildMLTestFiles(title, slug, testDir, autoGenerate) {
    return [
        {
            path: `${testDir}/ml/test_${slug}.py`,
            framework: 'pytest',
            content: buildMLTestContent(title),
            ready: autoGenerate,
        },
        // SPEC-015b: robustness + reproducibility tests — delegated to separate module
        buildMLRobustnessTestFile(title, slug, testDir, autoGenerate),
    ];
}
//# sourceMappingURL=platform-test-templates.js.map