/*
 * 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 { generateNetzeroWorkflows } from '../generators/workflows/netzero.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const netzeroProfile = {
    id: 'netzero',
    label: 'Net Zero Cloud',
    ruleFile: 'netzero-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/StnryAssetEnvrSrc')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/BldgEnergyIntensity')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/SustainabilityCloud')));
    },
    workflows: generateNetzeroWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Net Zero Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Net Zero Cloud Standards',
            '',
            '> Role: Net Zero Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Net Zero Cloud provides carbon accounting, energy management, and ESG reporting capabilities. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Net Zero Cloud data model and sustainability configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Net Zero Cloud Data Model (CRITICAL)',
            '- **Carbon Accounting** is the foundation — tracks greenhouse gas emissions across Scope 1, 2, and 3.',
            '- **Energy Management** tracks building energy consumption, fleet vehicle emissions, and renewable energy credits.',
            '- **ESG Reporting** aligns emission data with disclosure frameworks (GRI, SASB, TCFD, CDP).',
            '- **Waste & Water Tracking** monitors waste generation, diversion rates, and water consumption.',
            '',
            '### Core Net Zero Cloud Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Stationary Asset Env Source | `StnryAssetEnvrSrc` | Fixed-location emission sources (boilers, furnaces, generators) |',
            '| Building Energy Intensity | `BldgEnergyIntensity` | Energy use per building — grid electricity, natural gas, renewables |',
            '| Vehicle Asset Env Source | `VhclAssetEnvrSrc` | Fleet and mobile emission sources (company vehicles, business travel) |',
            '| Sustainability Goal | `SustainabilityGoal` | Reduction targets aligned to SBTi pathways |',
            '| Carbon Footprint | `CarbonFootprint` | Aggregated emissions per scope, period, and organizational unit |',
            '| Emissions Source | `EmissionsSource` | Individual emission source records with factor linkage |',
            '| Energy Use Record | `EnergyUseRecord` | Granular energy consumption data (meter readings, utility bills) |',
            '',
            '## Carbon Accounting',
            '',
            '### Scope Classification',
            '- **Scope 1 (Direct Emissions):** Company-owned or controlled sources — stationary combustion, mobile sources, fugitive emissions, process emissions.',
            '- **Scope 2 (Indirect — Electricity):** Purchased electricity, steam, heating, and cooling. Report both location-based and market-based methods.',
            '- **Scope 3 (Value Chain):** All other indirect emissions — purchased goods, business travel, employee commuting, waste, downstream transport, use of sold products.',
            '',
            '### Calculation Methodology',
            '- Activity Data × Emission Factor = CO2e (carbon dioxide equivalent).',
            '- Always store raw activity data (kWh, liters, km) separately from calculated emissions.',
            '- Never hardcode emission factors in Apex — use reference data records with effective date ranges.',
            '- Support both activity-based and spend-based estimation methods for Scope 3.',
            '',
            '## Emission Factors',
            '',
            '### Factor Library Management',
            '- Maintain factor libraries as reference data with versioned effective dates.',
            '- Standard libraries: **EPA eGRID** (US grid), **DEFRA** (UK GHG factors), **IEA** (global energy).',
            '- Custom factor creation: required when standard libraries do not cover organization-specific sources.',
            '- Annual refresh: emission factors change yearly — configure a scheduled review process.',
            '- Factor selection logic: match source type + fuel type + geography + reporting year to the correct factor.',
            '',
            '### Factor Data Quality',
            '- Track factor provenance: library name, version, publication date, geographic scope.',
            '- Flag stale factors: any factor beyond its publication year requires review before use in calculations.',
            '- Audit trail: log which factor was applied to each emission calculation for assurance readiness.',
            '',
            '## Energy Management',
            '',
            '### Building Energy Tracking',
            '- Use `BldgEnergyIntensity` to track energy consumption per facility.',
            '- Key metrics: total consumption (kWh), energy intensity (kWh/sqft or kWh/sqm), renewable percentage.',
            '- Separate grid electricity (Scope 2) from on-site generation (Scope 1 if fossil, zero if renewable).',
            '- Track Renewable Energy Credits (RECs) and Power Purchase Agreements (PPAs) for market-based Scope 2.',
            '',
            '### Fleet Vehicle Emissions',
            '- Use `VhclAssetEnvrSrc` for company-owned and leased vehicles.',
            '- Track by fuel type (diesel, gasoline, electric, hybrid), distance, and fuel consumed.',
            '- Scope 1: company-owned/leased vehicles under operational control.',
            '- Scope 3 Category 6: business travel in non-company vehicles.',
            '- Scope 3 Category 7: employee commuting.',
            '',
            '### Renewable Energy Credits',
            '- Track REC purchases with: certificate ID, vintage year, generation source, MWh quantity.',
            '- RECs reduce market-based Scope 2 — they do NOT reduce location-based Scope 2.',
            '- Never double-count: a REC can only be applied once to one reporting boundary.',
            '',
            '## ESG Reporting',
            '',
            '### Framework Alignment',
            '- **GRI (Global Reporting Initiative):** GRI 305 (Emissions), GRI 302 (Energy), GRI 303 (Water), GRI 306 (Waste).',
            '- **SASB (Sustainability Accounting Standards Board):** Industry-specific metrics — GHG intensity per revenue or output.',
            '- **TCFD (Task Force on Climate-related Financial Disclosures):** Governance, Strategy, Risk Management, Metrics & Targets.',
            '- **CDP (Carbon Disclosure Project):** Annual climate questionnaire — Scope 1/2/3 emissions, targets, climate risks.',
            '',
            '### Disclosure Automation',
            '- Map each framework disclosure question to the Net Zero Cloud field that provides the answer.',
            '- Use Custom Metadata to maintain framework-to-field mappings (updateable without deployment).',
            '- Automate data pull for recurring disclosures — reduce manual aggregation errors.',
            '- Version control all reported figures with snapshot records per reporting period.',
            '',
            '## Forecasting & Targets',
            '',
            '### Science-Based Targets (SBTi)',
            '- Use `SustainabilityGoal` to store approved reduction targets.',
            '- Key attributes: base year, base year emissions, target year, reduction percentage, scope coverage, pathway (1.5°C or well-below 2°C).',
            '- Interim milestones: SBTi requires near-term (5-10 year) targets — configure milestone records.',
            '- Track actual vs required reduction trajectory per reporting period.',
            '',
            '### Reduction Pathways',
            '- Model intervention scenarios: renewable energy procurement, fleet electrification, supplier engagement, energy efficiency.',
            '- Compare BAU (business as usual) trajectory against target-aligned reduction curve.',
            '- Use `CarbonFootprint` records to store both actual and forecasted emissions per period.',
            '',
            '### Scenario Modeling',
            '- Configure multiple scenarios per goal (optimistic, realistic, pessimistic).',
            '- Track intervention costs and expected emission reductions per initiative.',
            '- Dashboard visualization: overlay scenario curves against actual emissions trajectory.',
            '',
            '## Audit Trail & Data Lineage',
            '',
            '### Regulatory Compliance',
            '- Enable Field History Tracking on all emission source objects (CO2e, consumption quantity, emission factor).',
            '- Maintain calculation methodology documentation per source type.',
            '- Store supporting evidence (utility bills, invoices, supplier declarations) as Files linked to source records.',
            '- Version emission factors: retain historical factors applied in prior reporting periods.',
            '',
            '### Change Tracking',
            '- All changes to reported emission values must be traceable to a specific user and timestamp.',
            '- Configure Setup Audit Trail monitoring for emission factor and goal changes.',
            '- For third-party assurance: provide a clear data lineage from raw input to reported aggregate.',
            '',
            '## Integration Patterns',
            '',
            '### Utility Bill Data Import',
            '- Configure CSV import templates or API connectors for monthly utility bill ingestion.',
            '- Map bill fields: account number, meter ID, consumption (kWh/therms), billing period, cost.',
            '- Validate imported data against prior periods — flag anomalies exceeding 20% variance.',
            '',
            '### IoT Sensor Feeds',
            '- Use Platform Events for real-time meter data ingestion.',
            '- Batch-process sensor readings via Queueable Apex into `EnergyUseRecord` entries.',
            '- Handle dropped/duplicate readings with idempotent upsert logic (external ID on meter + timestamp).',
            '',
            '### Supply Chain Data from ERP',
            '- Define integration contracts for supplier-provided emission data (API or file-based).',
            '- Use Named Credentials for authenticated callouts to ERP systems.',
            '- Track data quality per supplier: primary activity data vs spend-based estimates vs industry averages.',
            '',
            '## Security & Data Governance',
            '',
            '### ESG Data Governance',
            '- Emission data is regulatory-sensitive — treat with the same rigor as financial data.',
            '- Use Permission Sets (not Profiles) to control access to emission source objects and fields.',
            '- Sustainability team: full CRUD on all Net Zero Cloud objects.',
            '- Executives: read-only access to dashboards and aggregated data.',
            '- External auditors: read-only access scoped to the reporting period under assurance.',
            '',
            '### Role-Based Access',
            '- Implement sharing rules to limit facility-level data visibility by region or business unit.',
            "- Use Restriction Rules for multi-tenant orgs where divisions should not see each other's emissions.",
            '- Never expose raw emission factor libraries to non-admin users — factors are reference data managed centrally.',
            '',
            '## Testing Net Zero Cloud',
            '- **Test factories for emission records:** Create `StnryAssetEnvrSrc`, `VhclAssetEnvrSrc`, and `BldgEnergyIntensity` records with known activity data and factors for deterministic CO2e assertions.',
            '- **Energy data testing:** Validate kWh-to-CO2e calculations across different factor libraries and effective dates.',
            '- **Sustainability goal testing:** Assert progress calculations against known base year and current year emissions.',
            '- **Integration testing:** Mock utility bill import and IoT sensor Platform Events to verify data ingestion pipelines.',
            '- Assign Net Zero Cloud Permission Sets to test users in `@TestSetup`.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Net Zero Cloud References',
            '- Net Zero Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.sustainability_cloud.meta/sustainability_cloud/',
            '- Net Zero Cloud Object Reference: https://developer.salesforce.com/docs/atlas.en-us.sustainability_cloud_object_reference.meta/sustainability_cloud_object_reference/',
            '- Carbon Accounting Guide: https://help.salesforce.com/s/articleView?id=sf.netzero_carbon_accounting.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('netzero'),
            '',
            ...interactionPreferences('Net Zero Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=netzero.js.map