import * as vscode from 'vscode';
import * as fs from 'fs';
import { getConfig } from '../config';
import { logInfo, logWarn, logError } from '../utils';

/**
 * HealthCheckMonitor: Periodically monitors the environment 
 * (Ollama, Disk, API) to ensure the agent stays functional.
 * 
 * Properly tracks the interval timer for cleanup on deactivation.
 */
export class HealthCheckMonitor {
    private static intervalHandle: ReturnType<typeof setInterval> | null = null;

    public static async runAllChecks(): Promise<{ ok: boolean; reports: string[] }> {
        const reports: string[] = [];
        const config = getConfig();

        // 1. AI Engine Connectivity Check
        try {
            const res = await fetch(`${config.ollamaUrl}/api/tags`, { signal: AbortSignal.timeout(3000) });
            if (res.ok) {
                logInfo('Health Check: AI engine connectivity OK.');
            } else {
                reports.push('AI Server is reachable but returned an error.');
            }
        } catch {
            reports.push('AI Server is NOT reachable. Please check if it is running.');
        }

        // 2. Workspace Validation
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders || workspaceFolders.length === 0) {
            reports.push('No workspace folder open. Agent capabilities will be limited.');
        }

        // 3. Simple Disk/Permissions Check
        try {
            const testFile = workspaceFolders ? vscode.Uri.joinPath(workspaceFolders[0].uri, '.g1-health-check') : null;
            if (testFile) {
                await vscode.workspace.fs.writeFile(testFile, Buffer.from('ok'));
                await vscode.workspace.fs.delete(testFile);
                logInfo('Health Check: Write permissions OK.');
            }
        } catch {
            reports.push('Write permissions denied in the current workspace.');
        }

        if (reports.length > 0) {
            logWarn(`Health Check Warnings: ${reports.join(' | ')}`);
            vscode.window.showWarningMessage(`Astra Health Warning: ${reports[0]}`);
        }

        return {
            ok: reports.length === 0,
            reports
        };
    }

    public static startInterval(ms: number = 300000) {
        // Prevent duplicate intervals
        if (this.intervalHandle !== null) {
            clearInterval(this.intervalHandle);
        }
        this.intervalHandle = setInterval(() => this.runAllChecks(), ms);
    }

    /**
     * Stops periodic health checks and releases resources.
     * Should be called from extension.deactivate().
     */
    public static dispose(): void {
        if (this.intervalHandle !== null) {
            clearInterval(this.intervalHandle);
            this.intervalHandle = null;
            logInfo('Health Check: Interval stopped.');
        }
    }
}
