/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { generateMulesoftWorkflows } from '../generators/workflows/mulesoft.js';
import { codebaseContextualization, consultativeDesign, documentationStandards, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, salesforceReferences, semanticCommits, } from './shared-sections.js';
export const mulesoftProfile = {
    id: 'mulesoft',
    label: 'MuleSoft Architect / Developer',
    ruleFile: 'mulesoft-standards.mdc',
    extensions: [
        'humao.rest-client',
        'blzjns.vscode-raml',
        'rangav.vscode-thunder-client',
        'redhat.vscode-xml',
        'redhat.vscode-yaml',
    ],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'auto-attach',
    globs: ['**/*.raml', '**/*.dwl', '**/mule-artifact.json', 'pom.xml', 'src/main/mule/**/*.xml'],
    workflows: generateMulesoftWorkflows,
    detect(cwd) {
        return existsSync(join(cwd, 'mule-artifact.json')) || existsSync(join(cwd, 'pom.xml'));
    },
    ruleContent() {
        return [
            '---',
            'description: MuleSoft Architect / Developer Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# MuleSoft Architect / Developer Standards',
            '',
            '> Role: MuleSoft Architect / Developer — Salesforce Professional Services.',
            '',
            ...codebaseContextualization('existing Mule project files, RAML/OAS specs, and `mule-app.properties`'),
            '',
            ...consultativeDesign('API design decisions (RAML vs OAS, sync vs async)'),
            '',
            '## API Design First',
            '- Define APIs using **RAML** or **OAS 3.0** before implementing any Mule flow.',
            '- Publish API specs to **Anypoint Exchange** before development starts.',
            '- Use **API Fragments** (traits, resource types, data types) for reusability.',
            '',
            '## Integration Patterns',
            '- Use **Named Credentials** on the Salesforce side for all outbound connections.',
            '- Never hardcode endpoints, credentials, or environment-specific values in flows.',
            '- Use **External Properties** (`mule-app.properties`) for environment-specific config.',
            '- Apply the **API-led Connectivity** model: System → Process → Experience layers.',
            '',
            '## Error Handling',
            '- Every flow must have an explicit **On Error Propagate** or **On Error Continue** scope.',
            '- Log errors using the standard Logger component before re-throwing.',
            '- Return meaningful HTTP status codes (4xx for client errors, 5xx for server errors).',
            '- Never swallow exceptions silently.',
            '',
            '## Security',
            '- Enforce **OAuth 2.0** or **Client ID Enforcement** on all Experience APIs.',
            '- Use **Secure Properties** (encrypted) for sensitive configuration values.',
            '- Apply **IP Allowlisting** at the API Gateway level where applicable.',
            '',
            '## Performance & Reliability',
            '- Use **Batch Processing** for large dataset operations (> 200 records).',
            '- Apply **Until Successful** scope for retry logic with exponential backoff.',
            '- Avoid synchronous flows for long-running operations — use async with callbacks.',
            '',
            '## Testing',
            '- Write **MUnit** tests for all flows. Target 80% coverage minimum.',
            '- Mock all external dependencies in MUnit tests (no live calls in tests).',
            '- Test both happy path and error scenarios.',
            '',
            '## DataWeave Standards',
            '- Name DataWeave modules descriptively: `transformContactToCanonical.dwl`, `mapOrderLineItems.dwl`.',
            '- Extract reusable transformations into `/src/main/resources/dwl/` modules.',
            '- Write DataWeave unit tests using MUnit `dw::test` framework for complex transformations.',
            '- Avoid inline DataWeave in flows — externalize all non-trivial transformations to `.dwl` files.',
            '- Handle null/missing fields explicitly with `default` operator — never assume field presence.',
            '',
            '## API Naming & Versioning',
            '- Follow **API-led naming**: `sys-<system>-api`, `proc-<process>-api`, `exp-<experience>-api`.',
            '- URL-based versioning: `/api/v1/`, `/api/v2/`. Never break existing consumers without version bump.',
            '- Deprecation policy: announce deprecation 2 sprints before removal. Document in API spec.',
            '- API lifecycle: Design → Implement → Test → Publish → Deprecate → Retire.',
            '',
            '## CloudHub 1.0 vs CloudHub 2.0',
            '- **New implementations MUST use CloudHub 2.0 (CH2).** CloudHub 1.0 is in maintenance mode.',
            '- CH2 is container-based (Docker/Kubernetes). Deployment target: `cloudhub2`. Worker sizing uses vCores + replicas.',
            '- CH2 key differences: no shared load balancers (use Flex Gateway), no mule-app.properties file in the UI (use Secure Properties Tool + properties files).',
            '- **Runtime Fabric (RTF):** for on-premise or private cloud Kubernetes deployments. Use when data residency or network isolation is required.',
            '- **Flex Gateway:** replaces legacy API Manager gateways for CH2. Deploy as a Docker container or Kubernetes sidecar. Manages policies, rate limiting, and client enforcement.',
            '- Migration from CH1 to CH2: involves rewriting deployment descriptors. Treat as an ADR decision — document the migration plan.',
            '',
            '## Anypoint MQ (Async Messaging)',
            '- Use **Anypoint MQ** for async, decoupled communication between Mule applications and external systems.',
            '- **Queue** (point-to-point): one producer, one consumer. Use for task processing, guaranteed delivery.',
            '- **Exchange** (pub/sub): one producer, many consumers. Use for event fan-out.',
            '- **FIFO Queue:** use when message ordering is critical (e.g., order lifecycle events). Higher cost — only when strictly needed.',
            '- **Dead Letter Queue (DLQ):** every production queue must have a DLQ. Configure `maxRedelivery` and route to DLQ on failure.',
            '- Correlation with Salesforce: Platform Events → external system use `sf-mule-bridge` pattern or direct HTTP. For high-volume: Anypoint MQ decouples the spike.',
            '- Always set message TTL aligned with business SLA. Default TTL (7 days) is not acceptable for all use cases.',
            '',
            '## MuleSoft Deployment',
            '- Target environments: **CloudHub 2.0** (SaaS) preferred. **Runtime Fabric** for private cloud/on-premise. **Standalone** only for legacy.',
            '- CI/CD: use `mule-maven-plugin` for automated deployment. Pipeline: build → MUnit → deploy → health check.',
            '- Never hardcode environment-specific values — use `mule-app.properties` with environment-specific overrides.',
            '- After deployment: verify the health endpoint and check Anypoint Monitoring for errors.',
            '- This replaces the standard `sf project deploy` workflow — MuleSoft has its own deployment lifecycle.',
            '',
            '## MuleSoft AI Chain (Agentforce + MuleSoft)',
            '- **MuleSoft AI Chain** connects Mule flows with Agentforce actions and LLM capabilities via HTTP.',
            '- Use when: an Agentforce agent needs to call a complex integration (ERP, SAP, legacy system) that is already exposed as a Mule API.',
            '- Pattern: Agentforce invocable action → HTTP callout → Mule Experience API → System API → external system.',
            '- **Configure the Mule Experience API as a Named Credential** in Salesforce — the Agentforce action invokes it securely.',
            '- Use **MuleSoft AI Chain connector** for orchestrating LLM calls within Mule flows: chain prompt → transform → external API → response assembly.',
            '- AI Chain use cases: enriching Salesforce records with ERP data before agent response, multi-system data aggregation for agent context, async processing triggered by an agent action.',
            '- Never call external LLMs directly from Apex when a Mule API already handles the integration — route through the existing API layer.',
            '- Document the Agentforce → MuleSoft boundary in `/docs/integrations/ai-chain.md`: action name, Mule API endpoint, data mapping, error handling.',
            '',
            '## MuleSoft Composer (Low-Code)',
            '- **MuleSoft Composer** is the no-code integration tool for business users — connects Salesforce with common SaaS apps (Slack, Google Sheets, Workday, NetSuite) via point-and-click.',
            '- **Use Composer when:** the integration is simple (field sync, record creation trigger, notification), the owner is a business analyst or admin, and no transformation logic is required.',
            '- **Use Anypoint Studio when:** complex DataWeave transformations, custom error handling, high-volume batch processing, or the integration requires Runtime Fabric deployment.',
            '- Never rebuild a Composer flow in Anypoint Studio just to "make it proper" — Composer is supported and maintains itself.',
            '- Composer flows cannot be version-controlled in Git — document them in `/docs/integrations/composer-flows.md` with screenshots and field mappings.',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            ...semanticCommits(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: API spec location, API-led layer being implemented,',
            '  external system endpoints (from Named Credentials), and error handling strategy.',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('mulesoft'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=mulesoft.js.map