/*
 * 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 { generateCgcloudWorkflows } from '../generators/workflows/cgcloud.js';
import { codebaseContextualization, documentationStandards, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, salesforceReferences, semanticCommits, } from './shared-sections.js';
function hasCGCloudNamespace(cwd) {
    const packageXml = join(cwd, 'package.xml');
    if (existsSync(packageXml)) {
        const content = readFileSync(packageXml, 'utf8');
        if (content.includes('cgcloud__'))
            return true;
    }
    const sfdxProject = join(cwd, 'sfdx-project.json');
    if (existsSync(sfdxProject)) {
        const content = readFileSync(sfdxProject, 'utf8');
        if (content.toLowerCase().includes('cgcloud'))
            return true;
    }
    return false;
}
export const cgcloudProfile = {
    id: 'cgcloud',
    label: 'Consumer Goods Cloud (CGCloud)',
    ruleFile: 'cgcloud-standards.mdc',
    extensions: ['sqrtt.prophet', 'salesforce.commercedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        return hasCGCloudNamespace(cwd);
    },
    workflows: generateCgcloudWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Consumer Goods Cloud (CGCloud) Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Consumer Goods Cloud (CGCloud) Standards',
            '',
            '> Role: CGCloud Developer / Configurator — Salesforce Professional Services.',
            '',
            ...codebaseContextualization('existing CGCloud CMDT records, Modeler configuration, and `cgcloud__` references'),
            '',
            '## Consultative Design (CRITICAL)',
            '- **No Ninja Edits.** Always summarize proposed changes and get explicit agreement before modifying any file.',
            '- Provide pros/cons when choosing between Modeler configuration and custom code.',
            '',
            '## Managed Package Rules (CRITICAL)',
            '- **Never modify managed package components** (`cgcloud__` prefix). They are read-only.',
            "- All customizations must use CGCloud's official **extension points** only.",
            '- Customizing outside extension points breaks upgrade paths and is unsupported.',
            '',
            '## Modeler Config First',
            '- Before writing Apex or LWC, ask: *"Can this be solved with Modeler configuration?"*',
            '- Modeler controls: Promotion Types, Activity Types, Product Hierarchy mapping, KPI definitions, Split-level config.',
            '- Configuration changes in Modeler (CMDT records) must be deployed before dependent Apex.',
            '',
            '## Namespace Awareness',
            "- All custom fields, classes, and components extending CGCloud must follow the project's naming prefix (not `cgcloud__`).",
            '- When querying CGCloud objects, always use the full `cgcloud__` prefix in SOQL.',
            '- Never use `SELECT *` equivalents — CGCloud objects have deep schemas; select only required fields.',
            '',
            '## CGCloud Data Model',
            '- Understand the hierarchy: Account → Territory → Route → Activity Plan → Activity.',
            '- Promotion and ActivityPlan queries are expensive — always filter by status and date range.',
            '- Fiscal calendar dependencies must be considered in any date-based query.',
            '',
            '## Deployment Order',
            '- Deploy CMDT (Modeler records) before Apex that depends on them.',
            '- Never deploy CGCloud configuration changes and custom Apex in the same changeset if avoidable.',
            '- Validate in a CGCloud-configured sandbox before deploying to production.',
            '',
            '## Personas & Permission Sets',
            '- CGCloud users have specific PSGs: Field Rep, Territory Manager, Back Office.',
            '- Always test business logic under each relevant persona using `System.runAs()`.',
            '- Never bypass CGCloud sharing rules — they enforce territory-based data visibility.',
            '',
            '## Product Variant Awareness',
            '- CGCloud covers three product variants — configuration patterns differ significantly:',
            '  - **TPM (Trade Promotion Management):** Promotion Types, Funds, Spending, KPI definitions.',
            '  - **Retail Execution:** Activity Plans, Store Surveys, Visit Templates, Planogram compliance.',
            '  - **Route Optimization:** Territory definitions, Route Plans, visit frequency rules.',
            '- Always confirm which variant is in scope before configuring. Never mix configuration patterns across variants.',
            '',
            '## CGCloud Mobile SDK / Offline Execution',
            '- **Field Reps operate offline.** Design all Retail Execution and Route Optimization features with offline-first in mind.',
            '- The CGCloud Mobile SDK caches a subset of records for offline use — data volume limits apply per device.',
            '- **Offline dataset design:** minimize the number of objects and fields synced. Never sync large blobs or unnecessary relationships.',
            '- **Conflict resolution:** CGCloud uses last-write-wins for most field conflicts. For critical business fields, define explicit merge rules in Modeler.',
            '- **Sync triggers:** sync happens on app open and on explicit user action. Do not assume real-time data in offline sessions.',
            '- Test offline scenarios explicitly: create records offline, go online, verify sync and conflict resolution.',
            '- Test on actual mobile simulators (iOS/Android) — some UI behaviors differ from desktop.',
            '',
            '## CGCloud Upgrade Lifecycle',
            "- CGCloud releases follow Salesforce's 3-release-per-year cadence (Spring / Summer / Winter) but also has its own minor version cycle.",
            '- **Before every Salesforce org upgrade:** verify the CGCloud package version compatibility matrix.',
            '- Run a **regression test suite** (all CGCloud business flows) in a sandbox that has been upgraded before approving production upgrade.',
            '- Assign an owner for the upgrade testing cycle — do not let sandbox upgrades happen without a test run.',
            '- Extension point behavior can change between package versions — review CGCloud release notes for breaking changes.',
            '- Document the current CGCloud package version in `sfdx-project.json` and in `/docs/cgcloud/version-log.md`.',
            '',
            '## CGCloud Test Data',
            '- Test data for `cgcloud__` objects requires specific parent records (Account → Territory → Route).',
            '- Use a namespace-aware **TestDataFactory** that creates the full CGCloud object hierarchy.',
            '- Test under each CGCloud persona: Field Rep (mobile), Territory Manager (supervisor), Back Office (admin).',
            '- Modeler config (CMDT) must be deployed to the test org BEFORE running tests that depend on CGCloud logic.',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            ...semanticCommits(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: which CGCloud product (TPM / Retail Execution / Route Optimization),',
            '  the extension point being used, the Modeler config already in place, and the PSG for test users.',
            '- When the task touches business object design (SLAs, approvals, milestones, routing rules,',
            '  entitlements), delegate evaluation to **Architect** or **BA** before proposing a custom',
            '  cgcloud__ extension object that duplicates native Sales or Service Cloud configuration.',
            '',
            ...salesforceReferences(),
            '',
            '### CG Cloud Enhanced Data Model',
            '- When asked to use or evaluate the Enhanced Data Model, refer to:',
            '  https://help.salesforce.com/s/articleView?id=ind.cg_concept_understand_enhancedmodel.htm&type=5',
            '- Always confirm with the customer whether the Enhanced Model is enabled before designing object extensions.',
            ...getSharedSectionLines('cgcloud'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=cgcloud.js.map