/**
 * Vigthoria Rules Provider — .vigthoriarules Support
 * 
 * Reads project-level custom instructions from .vigthoriarules files.
 * These instructions are prepended to every AI system prompt,
 * similar to .cursorrules in Cursor.
 * 
 * Supports:
 * - .vigthoriarules (primary)
 * - .vigthoria/rules (directory format)
 * - Workspace settings override
 * - Hierarchical rules (workspace root + subfolder)
 * - Live reload via file watchers
 */

const vscode = require('vscode');
const path = require('path');

class VigthoriRulesProvider {
    constructor() {
        this.rules = '';               // Current active rules text
        this.rulesFilePath = null;     // Path to active rules file
        this.fileWatcher = null;
        this.statusBarItem = null;
        this.isActive = false;
        
        // Supported file names (checked in order of priority)
        this.ruleFileNames = [
            '.vigthoriarules',
            '.vigthoria/rules',
            '.vigthoria/rules.md',
            '.vigthoria/instructions',
            '.vigthoria-rules',
        ];

        console.log('[RULES-PROVIDER] ✨ Initialized');
    }

    register(context) {
        // Commands
        context.subscriptions.push(
            vscode.commands.registerCommand('vigthoria.openRulesFile', () => this.openOrCreateRulesFile()),
            vscode.commands.registerCommand('vigthoria.reloadRules', () => this.loadRules()),
            vscode.commands.registerCommand('vigthoria.showRules', () => this.showCurrentRules()),
        );

        // Status bar
        this.statusBarItem = vscode.window.createStatusBarItem(
            vscode.StatusBarAlignment.Right, 96
        );
        this.statusBarItem.command = 'vigthoria.openRulesFile';
        this.statusBarItem.text = '$(law) No rules';
        this.statusBarItem.tooltip = 'Vigthoria Rules — Click to create .vigthoriarules';
        this.statusBarItem.show();
        context.subscriptions.push(this.statusBarItem);

        // Watch for rules file changes
        if (vscode.workspace.workspaceFolders?.length > 0) {
            const watchers = [
                vscode.workspace.createFileSystemWatcher('**/.vigthoriarules'),
                vscode.workspace.createFileSystemWatcher('**/.vigthoria/rules'),
                vscode.workspace.createFileSystemWatcher('**/.vigthoria/rules.md'),
                vscode.workspace.createFileSystemWatcher('**/.vigthoria/instructions'),
                vscode.workspace.createFileSystemWatcher('**/.vigthoria-rules'),
            ];

            for (const watcher of watchers) {
                watcher.onDidChange(() => this.loadRules());
                watcher.onDidCreate(() => this.loadRules());
                watcher.onDidDelete(() => this.loadRules());
                context.subscriptions.push(watcher);
            }
        }

        // Watch workspace folder changes
        context.subscriptions.push(
            vscode.workspace.onDidChangeWorkspaceFolders(() => this.loadRules())
        );

        // Load rules on startup
        this.loadRules();

        console.log('[RULES-PROVIDER] ✅ Registered');
    }

    /**
     * Load rules from the workspace
     */
    async loadRules() {
        this.rules = '';
        this.rulesFilePath = null;
        this.isActive = false;

        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (!workspaceRoot) {
            this._updateStatusBar();
            return;
        }

        // 1. Check workspace settings first (highest priority override)
        const config = vscode.workspace.getConfiguration('vigthoria');
        const settingsRules = config.get('customInstructions', '');
        if (settingsRules && settingsRules.trim()) {
            this.rules = settingsRules.trim();
            this.isActive = true;
            this._updateStatusBar();
            console.log('[RULES-PROVIDER] Loaded rules from workspace settings');
            return;
        }

        // 2. Search for rules files (in priority order)
        for (const fileName of this.ruleFileNames) {
            const filePath = path.join(workspaceRoot, fileName);
            try {
                const uri = vscode.Uri.file(filePath);
                const data = await vscode.workspace.fs.readFile(uri);
                const content = Buffer.from(data).toString('utf-8').trim();
                
                if (content.length > 0) {
                    this.rules = content;
                    this.rulesFilePath = filePath;
                    this.isActive = true;
                    this._updateStatusBar();
                    console.log(`[RULES-PROVIDER] ✅ Loaded rules from ${fileName} (${content.length} chars)`);
                    return;
                }
            } catch {
                // File doesn't exist, try next
            }
        }

        // No rules found
        this._updateStatusBar();
        console.log('[RULES-PROVIDER] No rules file found');
    }

    /**
     * Get the current rules text for injection into system prompts
     */
    getRules() {
        return this.rules;
    }

    /**
     * Get a formatted system prompt prefix with rules
     */
    getSystemPromptPrefix() {
        if (!this.rules || !this.isActive) return '';

        return [
            '### Project-Specific Instructions (.vigthoriarules):',
            '',
            this.rules,
            '',
            '### End of project-specific instructions.',
            '',
        ].join('\n');
    }

    /**
     * Check if rules are active
     */
    hasRules() {
        return this.isActive && this.rules.length > 0;
    }

    /**
     * Open or create the rules file
     */
    async openOrCreateRulesFile() {
        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (!workspaceRoot) {
            vscode.window.showWarningMessage('No workspace open');
            return;
        }

        // If rules file exists, open it
        if (this.rulesFilePath) {
            const doc = await vscode.workspace.openTextDocument(this.rulesFilePath);
            await vscode.window.showTextDocument(doc);
            return;
        }

        // Create a new .vigthoriarules file
        const filePath = path.join(workspaceRoot, '.vigthoriarules');
        const template = this._getTemplate();

        const uri = vscode.Uri.file(filePath);
        const encoder = new TextEncoder();
        await vscode.workspace.fs.writeFile(uri, encoder.encode(template));

        const doc = await vscode.workspace.openTextDocument(uri);
        await vscode.window.showTextDocument(doc);

        vscode.window.showInformationMessage('✅ Created .vigthoriarules — Add your project-specific instructions here!');
        
        // Reload rules
        await this.loadRules();
    }

    /**
     * Show current rules in a preview
     */
    async showCurrentRules() {
        if (!this.isActive || !this.rules) {
            const create = await vscode.window.showInformationMessage(
                'No .vigthoriarules file found. Create one?',
                'Create', 'Cancel'
            );
            if (create === 'Create') {
                await this.openOrCreateRulesFile();
            }
            return;
        }

        // Show in a temporary document
        const doc = await vscode.workspace.openTextDocument({
            content: `# Active Vigthoria Rules\n# Source: ${this.rulesFilePath || 'Workspace Settings'}\n\n${this.rules}`,
            language: 'markdown'
        });
        await vscode.window.showTextDocument(doc, { preview: true });
    }

    // --- Private ---

    _getTemplate() {
        return `# Vigthoria Rules — Project-Specific AI Instructions
# These instructions are automatically included in every AI interaction.
# Similar to .cursorrules but more powerful.

## Project Overview
# Describe your project here so the AI understands the context.

## Tech Stack
# List your technologies, frameworks, and libraries.

## Coding Standards
# - Preferred patterns
# - Naming conventions
# - File structure

## Important Context
# - Architecture decisions
# - API endpoints
# - Database schema notes
# - Business logic rules

## DO
# - Follow existing code patterns
# - Write clear, documented code

## DON'T
# - Don't use deprecated APIs
# - Don't add unnecessary dependencies
`;
    }

    _updateStatusBar() {
        if (!this.statusBarItem) return;

        if (this.isActive) {
            const lines = this.rules.split('\n').filter(l => l.trim() && !l.trim().startsWith('#')).length;
            this.statusBarItem.text = `$(law) Rules: ${lines} directives`;
            this.statusBarItem.tooltip = `Vigthoria Rules active from ${this.rulesFilePath ? path.basename(this.rulesFilePath) : 'settings'}`;
            this.statusBarItem.color = undefined;
        } else {
            this.statusBarItem.text = '$(law) No rules';
            this.statusBarItem.tooltip = 'Click to create .vigthoriarules';
            this.statusBarItem.color = new vscode.ThemeColor('disabledForeground');
        }
    }

    dispose() {
        if (this.statusBarItem) this.statusBarItem.dispose();
    }
}

module.exports = { VigthoriRulesProvider };
