/*
 * 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 { generateEnergyWorkflows } from '../generators/workflows/energy.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const energyProfile = {
    id: 'energy',
    label: 'Energy & Utilities Cloud',
    ruleFile: 'energy-standards.mdc',
    extensions: ['salesforce.salesforcedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        return (existsSync(join(cwd, 'force-app/main/default/objects/EnergyUse')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/UtilityAccount')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/ServicePoint')));
    },
    workflows: generateEnergyWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Energy & Utilities Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Energy & Utilities Cloud Standards',
            '',
            '> Role: Energy & Utilities Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Energy & Utilities Cloud provides industry-specific data models and processes for electric, gas, and water utilities. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Energy & Utilities data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Energy & Utilities Data Model (CRITICAL)',
            '- **Premise-based model.** The utility data model is organized around physical locations (Premises),',
            '  points of delivery (Service Points), and metering devices (Utility Meters).',
            '- **Account hierarchy:** Utility Account → Premise → Service Point → Meter.',
            '  A single customer (Utility Account) may have multiple premises, each with multiple service points.',
            '- **Never create custom objects to track meters, readings, or service points** — use the native Energy & Utilities Cloud objects.',
            '',
            '### Core Energy & Utilities Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Service Point | `ServicePoint` | Point of delivery for a utility commodity (electric, gas, water) |',
            '| Premise | `Premise` | Physical location served by the utility |',
            '| Utility Account | `UtilityAccount` | Customer account for utility billing |',
            '| Utility Meter | `UtilityMeter` | Physical metering device at a service point |',
            '| Utility Meter Reading | `UtilityMeterReading` | Individual meter read (actual, estimated, adjusted) |',
            '| Energy Use Category | `EnergyUseCategory` | Classification of energy consumption patterns |',
            '| Rate Plan | `RatePlan` | Tariff schedule defining pricing structure |',
            '| Rate Plan Charge | `RatePlanCharge` | Individual charge component within a rate plan |',
            '| DER Program | `DERProgram` | Distributed Energy Resource program (solar, battery, demand response) |',
            '',
            '### Customer 360 for Utilities',
            '- **Utility Account** is the billing entity — maps to the customer relationship.',
            '- **Premise** represents the physical address and is the anchor for all service delivery.',
            '- One premise may have multiple service points (e.g., electric + gas at the same address).',
            '- Each service point has one active meter at a time (meter exchange creates a new meter record).',
            '- Use Account hierarchy for parent/subsidiary utility accounts (e.g., property management companies).',
            '',
            '## Meter Data Management',
            '- **Reading collection:** Support AMI (Advanced Metering Infrastructure) smart meter feeds,',
            '  AMR (Automated Meter Reading) drive-by collection, and manual field reads.',
            '- **Validation rules:** Configure high/low consumption thresholds, negative consumption detection,',
            '  and zero-consumption alerts for active service points.',
            '- **Estimation methods:** Linear interpolation, weather-adjusted estimation, historical average,',
            '  and similar-premises estimation for missing reads.',
            '- **Interval data:** Store 15-minute or hourly interval data for TOU billing and demand analysis.',
            '  Use bulk data patterns — never insert interval readings one-at-a-time in a loop.',
            '- **Smart meter integration:** Receive data via Platform Events or batch API from AMI headend systems',
            '  (Itron, Landis+Gyr, Sensus, Aclara). Validate before persisting.',
            '',
            '## Billing & Rate Plans',
            '- **Rate structure types:** Flat rate, tiered/inclining block, time-of-use (TOU),',
            '  demand charges, reactive power charges, and combination rates.',
            '- **Tiered rates:** Configure consumption blocks with ascending/descending unit prices.',
            '  Tier boundaries may be fixed or baseline-allocated (varies by household size or climate zone).',
            '- **Time-of-use pricing:** Define on-peak, mid-peak, off-peak periods with seasonal variation.',
            '  Link TOU schedules to calendar configurations for holiday exclusions.',
            '- **Demand charges:** Based on peak kW measured in 15/30/60-minute intervals.',
            '  Support ratcheted demand (percentage of highest peak in trailing 12 months).',
            '- **Net metering:** Credit customers for excess generation exported to the grid.',
            '  Configure export credit rates, monthly rollover, and annual true-up rules.',
            '- **Rate plan assignment:** Associate rate plans with service points or utility accounts.',
            '  Support rate plan transitions with effective/expiration dates.',
            '',
            '## Distributed Energy Resources (DER)',
            '- **DER Programs:** Solar, battery storage, demand response, virtual power plants, EV managed charging.',
            '- **Program enrollment:** Track customer participation via `DERProgram` junction records.',
            '  Manage eligibility criteria, incentive calculations, and enrollment lifecycle.',
            '- **Interconnection management:** Track solar/battery interconnection applications,',
            '  technical review status, and permission to operate (PTO) dates.',
            '- **Virtual power plants (VPP):** Aggregate DER assets for grid services.',
            '  Track dispatch signals, response performance, and settlement calculations.',
            '- **Net metering for DER:** Link generation meters to DER program enrollment.',
            '  Calculate credits based on program-specific export rates.',
            '',
            '## Outage Management',
            '- **Outage tracking:** Record outage events with affected premises, service points, and customer count.',
            '- **ETR (Estimated Time of Restoration):** Calculate and communicate restoration estimates.',
            '  Update ETR as crews report progress.',
            '- **Crew dispatch:** Integrate with OMS (Outage Management System) for crew assignment and routing.',
            '- **Customer notifications:** Trigger proactive outage notifications via preferred channel (SMS, email, app push).',
            '- **Outage history:** Maintain outage event records for reliability reporting (SAIDI, SAIFI, CAIDI metrics).',
            '',
            '## Customer Programs',
            '- **Demand response:** Enroll customers in load curtailment programs.',
            '  Track event notifications, participation confirmation, and performance measurement.',
            '- **Efficiency rebates:** Process rebate applications for energy-efficient equipment upgrades.',
            '  Track application status, inspection results, and payment processing.',
            '- **EV charging programs:** Manage EV charger enrollment, TOU rate assignment for EV charging,',
            '  and load management for grid-friendly charging schedules.',
            '- **Green energy opt-in:** Track renewable energy program subscriptions,',
            '  REC (Renewable Energy Certificate) allocation, and premium billing.',
            '',
            '## Integration Patterns',
            '- **AMI (Advanced Metering Infrastructure):** Bidirectional integration with meter headend systems.',
            '  Receive interval data and meter events; send remote commands (connect/disconnect, on-demand read).',
            '- **MDMS (Meter Data Management System):** VEE (Validation, Estimation, Editing) pipeline integration.',
            '  Receive validated reads; send raw reads for processing.',
            '- **CIS (Customer Information System):** Billing system integration for rate application,',
            '  bill calculation, payment processing, and account management.',
            '- **OMS (Outage Management System):** Real-time outage event sync, crew dispatch,',
            '  and ETR updates for customer communication.',
            '- **SCADA (Supervisory Control and Data Acquisition):** Monitor grid telemetry,',
            '  substation loading, and distribution automation events.',
            '- **GIS (Geographic Information System):** Premise and service point geocoding,',
            '  network connectivity model for outage analysis.',
            '- Use **Named Credentials** for all external system authentication — never embed credentials in Apex.',
            '- Prefer **Platform Events** for real-time event-driven integration (meter alerts, outage events).',
            '- Use **Batch Apex or Bulk API** for high-volume data loads (interval data, mass meter reads).',
            '',
            '## Security & Privacy',
            '- **Customer usage data privacy:** Meter reading and consumption data is utility-specific PII.',
            '  Apply FLS and sharing rules to restrict access to authorized personnel only.',
            '- **NERC CIP considerations:** For utilities subject to NERC CIP (Critical Infrastructure Protection),',
            '  ensure no bulk grid operational data is stored in Salesforce without appropriate controls.',
            '- **Third-party data sharing:** Green Button (ESPI) standard for customer-authorized data sharing.',
            '  Implement consent management for data release to third parties.',
            '- **PII fields:** Utility account numbers, SSN/Tax ID, consumption patterns, and premise addresses',
            '  are all sensitive. Apply encryption at rest where supported.',
            '',
            '## Testing Energy & Utilities',
            '- **Use TestDataFactory** to create Premises, Service Points, Utility Meters, and Meter Readings.',
            '- **Premise creation:** Always link to a parent Account (Utility Account) in test setup.',
            '- **Service Point creation:** Assign to a Premise with correct ServicePointType and Status.',
            '- **Meter Reading factories:** Generate sequences of readings with realistic consumption patterns',
            '  (not random values) to test validation rules and billing calculations.',
            '- **Rate Plan test data:** Create complete rate plan hierarchies (plan + charges + tiers)',
            '  to validate billing calculation logic end-to-end.',
            '- **Bulk testing:** Test with 200+ meter readings per service point to validate governor limit compliance.',
            '- Assign Energy & Utilities Permission Sets to test users in `@TestSetup`.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Energy & Utilities References',
            '- Energy & Utilities Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.energy_and_utilities_cloud.meta/energy_and_utilities_cloud/',
            '- Energy & Utilities Object Reference: https://developer.salesforce.com/docs/atlas.en-us.energy_and_utilities_cloud_object_reference.meta/energy_and_utilities_cloud_object_reference/',
            '- Utility Process Management: https://help.salesforce.com/s/articleView?id=sf.energy_utilities_overview.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('energy'),
            '',
            ...interactionPreferences('Energy & Utilities configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=energy.js.map