<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class InstallationLogger
{
    private static string $logChannel = 'installation';
    private static string $logFile = 'installation.log';

    /**
     * Log installation process with timestamp and context
     */
    public static function log(string $level, string $message, array $context = []): void
    {
        $timestamp = now()->format('Y-m-d H:i:s.u');
        $formattedMessage = "[{$timestamp}] INSTALLATION: {$message}";

        // Log to Laravel log
        Log::log($level, $formattedMessage, $context);

        // Also write to specific installation log file for easy access
        self::writeToInstallationLog($level, $formattedMessage, $context);
    }

    /**
     * Info level log
     */
    public static function info(string $message, array $context = []): void
    {
        self::log('info', $message, $context);
    }

    /**
     * Error level log
     */
    public static function error(string $message, array $context = []): void
    {
        self::log('error', $message, $context);
    }

    /**
     * Warning level log
     */
    public static function warning(string $message, array $context = []): void
    {
        self::log('warning', $message, $context);
    }

    /**
     * Debug level log
     */
    public static function debug(string $message, array $context = []): void
    {
        self::log('debug', $message, $context);
    }

    /**
     * Write directly to installation log file
     */
    private static function writeToInstallationLog(string $level, string $message, array $context = []): void
    {
        try {
            $logEntry = strtoupper($level) . ": {$message}";
            if (!empty($context)) {
                $logEntry .= " | Context: " . json_encode($context, JSON_UNESCAPED_SLASHES);
            }
            $logEntry .= PHP_EOL;

            // Write to storage/logs/installation.log
            $logPath = storage_path('logs/' . self::$logFile);
            file_put_contents($logPath, $logEntry, FILE_APPEND | LOCK_EX);
        } catch (\Exception $e) {
            // Fallback to Laravel log if file writing fails
            Log::error("InstallationLogger: Failed to write to installation log: " . $e->getMessage());
        }
    }

    /**
     * Get the installation log file path
     */
    public static function getLogPath(): string
    {
        return storage_path('logs/' . self::$logFile);
    }

    /**
     * Clear the installation log
     */
    public static function clearLog(): void
    {
        $logPath = self::getLogPath();
        if (file_exists($logPath)) {
            unlink($logPath);
        }
    }

    /**
     * Get the last N lines from installation log
     */
    public static function getLastLines(int $lines = 50): array
    {
        $logPath = self::getLogPath();
        if (!file_exists($logPath)) {
            return ['Installation log file not found'];
        }

        $content = file_get_contents($logPath);
        $allLines = explode(PHP_EOL, $content);

        return array_slice(array_filter($allLines), -$lines);
    }

    /**
     * Start installation log session
     */
    public static function startSession(): void
    {
        self::info("=== INSTALLATION SESSION STARTED ===");
        self::info("Session ID: " . uniqid());
        self::info("Timestamp: " . now()->toISOString());
        self::info("PHP Version: " . PHP_VERSION);
        self::info("Laravel Version: " . app()->version());
        self::info("Environment: " . app()->environment());
    }

    /**
     * End installation log session
     */
    public static function endSession(bool $success = true): void
    {
        if ($success) {
            self::info("=== INSTALLATION SESSION COMPLETED SUCCESSFULLY ===");
        } else {
            self::error("=== INSTALLATION SESSION FAILED ===");
        }
        self::info("Session ended at: " . now()->toISOString());
        self::info("");
    }
}