/*
 * 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, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { generateCrmaWorkflows } from '../generators/workflows/crma.js';
import { codebaseContextualization, documentationStandards, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, } from './shared-sections.js';
const CRMA_METADATA_TYPES = [
    'WaveApplication',
    'WaveDashboard',
    'WaveDataflow',
    'WaveRecipe',
    'WaveDataset',
    'WaveLens',
];
function hasCRMAMetadata(cwd) {
    const packageXml = join(cwd, 'package.xml');
    if (existsSync(packageXml)) {
        const content = readFileSync(packageXml, 'utf8');
        if (CRMA_METADATA_TYPES.some((t) => content.includes(t)))
            return true;
    }
    return false;
}
export const crmaProfile = {
    id: 'crma',
    label: 'CRM Analytics Engineer (CRMA)',
    ruleFile: 'analytics-standards.mdc',
    extensions: [
        'salesforce.analyticsdx-vscode',
        'salesforce.analyticsdx-vscode-core',
        'salesforce.analyticsdx-vscode-templates',
    ],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        return hasCRMAMetadata(cwd);
    },
    workflows: generateCrmaWorkflows,
    ruleContent() {
        return [
            '---',
            'description: CRM Analytics (CRMA / Tableau CRM) Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# CRM Analytics Standards (CRMA)',
            '',
            '> Role: Analytics Engineer — Salesforce Professional Services.',
            '> Inherits base rules from: salesforce-standards.mdc',
            '',
            ...codebaseContextualization('existing recipes, dataflows, dashboards, and SAQL queries'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Consultative Design (CRITICAL)',
            '- **No Ninja Edits.** Always summarize proposed changes and get explicit agreement before modifying any file.',
            '- Discuss data architecture (lineage, security predicates) before building dashboards or recipes.',
            '',
            '## Design Before Build',
            '- Before creating any dashboard or recipe, produce a data lineage diagram (Mermaid).',
            '- Document dataset dependencies: which dataflows/recipes produce each dataset.',
            '- Agree on the data model and field naming before building any lens or dashboard.',
            '',
            '## Data Architecture',
            '- **Recipe vs Dataflow:** Use Recipes (Data Prep) for new implementations. Dataflows are legacy.',
            '- Recipes run on a schedule — design with incremental loads in mind, not full refreshes.',
            '- Never load data that is not consumed by at least one dashboard or Calculated Insight.',
            '- Dataset names: **PascalCase**, descriptive, include the source system prefix (e.g., `SF_Opportunities`).',
            '',
            '## SAQL',
            '- Write SAQL queries with explicit `group by` and `order by` to avoid non-deterministic results.',
            '- Avoid `foreach` on large datasets — prefer `group` with aggregations.',
            '- Always test SAQL in the lens editor before embedding in a dashboard.',
            '- Filter early in the query pipeline — never load all records and filter at render time.',
            '',
            '## Row-Level Security',
            '- Every dataset that contains sensitive data **must** have a Security Predicate defined.',
            '- Test security predicates under each user persona before deploying.',
            '- Document the predicate logic in `/docs/analytics/security-predicates.md`.',
            '',
            '## Dashboard Design',
            '- Follow SLDS color guidelines for chart palettes — no custom hex colors without UX approval.',
            '- Every dashboard must have a documented "primary question" it answers.',
            '- Limit dashboard widgets to 12 per page — split into multiple pages if needed.',
            '- Always test dashboards on mobile viewport before release.',
            '',
            '## Deployment',
            '- Analytics metadata deployment order: Datasets → Dataflows/Recipes → Lenses → Dashboards → Apps.',
            '- Always validate recipe runs in sandbox before promoting to production.',
            '- Document manual post-deployment steps (schedule recipe runs, app sharing) in the release note.',
            '- Include `WaveApplication`, `WaveDashboard`, `WaveDataflow`, `WaveRecipe` in `package.xml`.',
            '',
            '## Testing',
            '- Validate dataset row counts before and after recipe runs.',
            '- Test each dashboard filter combination that appears in acceptance criteria.',
            '- Verify security predicates return correct data for at least 3 distinct user profiles.',
            '',
            '## Dashboard Embedding',
            '- Embed analytics dashboards in Lightning pages using the **CRM Analytics Dashboard** component.',
            '- When embedding in a record page: pass the record ID as a filter to scope the dashboard to the current record.',
            '- For custom LWC containers: use the `wave:waveDashboard` base component with `openLinksInNewWindow` for better UX.',
            '- Test embedded dashboards at all three responsive breakpoints (320px, 768px, 1280px).',
            '',
            '## Calculated Insights',
            '- **CI SQL (Data Cloud) vs SAQL CIs:** for new implementations with Data Cloud, use CI SQL (Data Cloud Calculated Insights) over SAQL-based CIs.',
            '- CI SQL runs against Data Cloud DMOs and outputs fields available on Unified Profiles and as segment criteria.',
            '- Write CI SQL with explicit aliases on all output fields. Use `GROUP BY` with all non-aggregated columns.',
            '- Validate CI output cardinality — unbounded growth breaks segment performance.',
            '- Always specify a refresh schedule aligned with the upstream Data Stream refresh.',
            '- Test CI with at least 3 months of historical data in sandbox before production.',
            '- SAQL-based CIs remain valid for CRMA-only datasets with no Data Cloud dependency.',
            '',
            '## Einstein Prediction Service',
            '- **Current product name is Einstein Prediction Service** (formerly Einstein Discovery). Einstein Prediction Builder is the legacy path.',
            '- Create prediction definitions in **Analytics Studio → Prediction Builder**. Review the generated model story before deploying.',
            '- Define: outcome variable, candidate predictors, and the training dataset. Review feature importance before production.',
            '- Deploy model scoring to Flows via the **Einstein Prediction** Flow element for real-time scoring on record save.',
            '- **Bring Your Own Model (BYOM):** for advanced use cases, register external ML models via the Prediction Service API.',
            '- Document model performance metrics (R², RMSE, AUC) and retrain cadence in `/docs/analytics/models.md`.',
            '- Monitor model drift: schedule quarterly retraining when accuracy drops >5% from baseline.',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            ...semanticCommits(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: dataset lineage diagram, security predicate definitions,',
            '  recipe schedule, dashboard primary question, and the user personas being tested.',
            '- When the task touches business object design (SLAs, approvals, milestones, routing rules,',
            '  entitlements), delegate evaluation to **Architect** or **BA** before proposing a custom',
            '  Analytics dataset or recipe that models a business process already manageable via native',
            '  Service Cloud or Sales Cloud configuration.',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('crma'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=crma.js.map