import pidusage from 'pidusage';

export type SystemState = 'active' | 'standby';

export interface SystemMetrics {
    cpu: number;
    memory: number; // in bytes
    memoryMB: number;
    uptime: number; // seconds
    state: SystemState;
    timestamp: number;
}

class SystemController {
    private state: SystemState = 'active'; // Default to active
    private lastMetrics: SystemMetrics | null = null;

    // Toggle System State
    toggle(): SystemState {
        this.state = this.state === 'active' ? 'standby' : 'active';
        console.log(`[God Mode] System State Toggled: ${this.state.toUpperCase()}`);
        return this.state;
    }

    // Set conform state
    setState(newState: SystemState) {
        this.state = newState;
    }

    getState(): SystemState {
        return this.state;
    }

    isActive(): boolean {
        return this.state === 'active';
    }

    // Get Live Resource Usage
    async getMetrics(): Promise<SystemMetrics> {
        try {
            const stats = await pidusage(process.pid);

            this.lastMetrics = {
                cpu: parseFloat(stats.cpu.toFixed(1)),
                memory: stats.memory,
                memoryMB: Math.round(stats.memory / 1024 / 1024),
                uptime: stats.elapsed,
                state: this.state,
                timestamp: Date.now()
            };

            return this.lastMetrics;
        } catch (e) {
            console.error("Failed to get pidusage", e);
            // Return cached or empty if fail
            return this.lastMetrics || {
                cpu: 0,
                memory: 0,
                memoryMB: 0,
                uptime: 0,
                state: this.state,
                timestamp: Date.now()
            };
        }
    }
}

export const system = new SystemController();
