"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextService = void 0;
const core_1 = require("@myycontext/core");
const logger_1 = require("../utils/logger");
const hybridAIClient_1 = require("../utils/hybridAIClient");
class ContextService {
    constructor(projectPath) {
        this.manifest = null;
        this.projectPath = projectPath;
        this.manifestManager = new core_1.DesignManifestManager(projectPath);
        this.aiClient = new hybridAIClient_1.HybridAIClient();
    }
    /**
     * Initialize and load the manifest
     */
    async initialize() {
        this.manifest = await this.manifestManager.loadDesignManifest();
    }
    /**
     * Get the full manifest
     */
    getManifest() {
        return this.manifest;
    }
    /**
     * Query specific data from the manifest
     */
    async queryContext(query) {
        if (!this.manifest) {
            await this.initialize();
        }
        if (!this.manifest) {
            throw new Error('Design manifest not found');
        }
        // Simple path-based lookup
        const parts = query.path.split('.');
        let current = this.manifest;
        for (const part of parts) {
            if (current && typeof current === 'object' && part in current) {
                current = current[part];
            }
            else {
                return null; // Path not found
            }
        }
        return current;
    }
    /**
     * Update specific metadata in the manifest
     */
    async updateManifest(updatePath, value) {
        if (!this.manifest) {
            await this.initialize();
        }
        if (!this.manifest) {
            throw new Error('Design manifest not found');
        }
        const parts = updatePath.split('.');
        let current = this.manifest;
        for (let i = 0; i < parts.length - 1; i++) {
            const part = parts[i];
            if (part === undefined)
                continue;
            if (!(part in current)) {
                current[part] = {};
            }
            current = current[part];
        }
        const lastPart = parts[parts.length - 1];
        if (lastPart !== undefined) {
            current[lastPart] = value;
        }
        logger_1.logger.info(`Updated manifest path '${updatePath}' with value:`, value);
    }
    /**
     * Save the manifest back to disk
     */
    async save() {
        if (!this.manifest) {
            throw new Error('No manifest loaded to save');
        }
        await this.manifestManager.saveDesignManifest(this.manifest);
    }
    /**
     * Get a consolidated enrichment context for the AI
     */
    async getEnrichedContext() {
        return this.manifestManager.enrichContextWithDesign("", "", "");
    }
    /**
     * Validate an intent against the Prime Objective
     * (Milestone 2: Hard Gravity)
     */
    async validateIntent(intent) {
        if (!this.manifest) {
            await this.initialize();
        }
        if (!this.manifest) {
            return { valid: true, narrativeWeight: 0.5 };
        }
        const primeObjective = this.manifest.phases.functional_summary.core_purpose;
        const projectNarrative = this.manifest.phases.design_intent.visual_philosophy;
        logger_1.logger.info(`Checking Hard Gravity for intent: "${intent}"`);
        const prompt = `You are the Hard Gravity Engine for Antigravity OS. 
Your job is to ensure that the AI Agent's intent aligns with the Project's Prime Objective.

PRIME OBJECTIVE: "${primeObjective}"
PROJECT NARRATIVE: "${projectNarrative}"

AGENT INTENT: "${intent}"

Does this intent align with the Prime Objective? 
Respond in JSON format:
{
  "aligns": true | false,
  "narrative_weight": 0.0 to 1.0,
  "reason": "Short explanation of alignment or deviation"
}

If the intent is a generic UI action (e.g., clicking a button to navigate), it should generally align unless it explicitly contradicts the objective.`;
        try {
            const response = await this.aiClient.generateText(prompt, {
                temperature: 0, // Deterministic
            });
            const result = JSON.parse(response.text.replace(/```json\n?|\n?```/g, '').trim());
            return {
                valid: result.aligns,
                reason: result.reason,
                narrativeWeight: result.narrative_weight
            };
        }
        catch (error) {
            logger_1.logger.error("Failed to validate intent against gravity", error);
            return { valid: true, narrativeWeight: 0.5 }; // Fallback
        }
    }
}
exports.ContextService = ContextService;
//# sourceMappingURL=ContextService.js.map