<?php

namespace FleekDash\Core;

use FleekDash\Core\DebugException;
use WP_REST_Response;

/**
 * Handles debug log copy, download URLs, and latest download.
 * Extracted from DebugController for S1448 compliance (method count).
 */
class DebugLogHandler
{
    private const DEBUG_LOG_FILE = '/debug.log';

    /** @var DebugLogService */
    private $logService;

    public function __construct(DebugLogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * Validate debug log exists and has content. Returns WP_REST_Response on error, null if valid.
     *
     * @param string $debug_log_path
     * @return WP_REST_Response|null
     */
    public function validateCopyDebugLogInput($debug_log_path)
    {
        $error = null;
        if (!file_exists($debug_log_path)) {
            $error = new WP_REST_Response(['success' => false, 'message' => 'Debug log file does not exist'], 404);
        } elseif (filesize($debug_log_path) === 0) {
            $error = new WP_REST_Response([
                'success' => false,
                'message' => 'Debug log is empty. No data to copy.',
                'data' => ['empty' => true],
            ], 400);
        } elseif (empty(trim(file_get_contents($debug_log_path)))) {
            $error = new WP_REST_Response([
                'success' => false,
                'message' => 'Debug log contains only whitespace. No data to copy.',
                'data' => ['empty' => true],
            ], 400);
        }
        return $error;
    }

    /**
     * Copy debug.log to uploads folder for easy download
     *
     * @return WP_REST_Response
     */
    public function copyDebugLogToUploads()
    {
        $debug_log_path = WP_CONTENT_DIR . self::DEBUG_LOG_FILE;
        $validationError = $this->validateCopyDebugLogInput($debug_log_path);
        if ($validationError !== null) {
            return $validationError;
        }

        try {
            $file_size = filesize($debug_log_path);

            $upload_dir = \wp_upload_dir();
            if ($upload_dir['error']) {
                throw new DebugException('Unable to access uploads directory: ' . $upload_dir['error']);
            }

            $timestamp = date('Y-m-d_H-i-s');
            $filename = 'debug-log-' . $timestamp . '.txt';
            $upload_path = $upload_dir['basedir'] . '/' . $filename;
            $upload_url = $upload_dir['baseurl'] . '/' . $filename;

            if (!copy($debug_log_path, $upload_path)) {
                throw new DebugException('Failed to copy debug.log to uploads folder');
            }

            // 0644 = owner rw, others r only (standard for log files)
            chmod($upload_path, 0644); // NOSONAR S2612

            $this->logService->clearDebugLog(false, false);

            if (function_exists('fleekdash_log_info')) {
                fleekdash_log_info('FleekDash Debug: Debug log copied to uploads and original cleared by user ID ' .
                    \get_current_user_id() . ' - File: ' . $filename . ' (' . round($file_size / 1024, 2) . ' KB)');
            }

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Debug log copied to uploads folder and original cleared',
                'data' => [
                    'filename' => $filename,
                    'url' => $upload_url,
                    'path' => $upload_path,
                    'size' => filesize($upload_path),
                    'timestamp' => $timestamp,
                    'original_cleared' => true,
                ],
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error copying debug log to uploads - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to copy debug log: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get download URL for the most recent debug log copy in uploads
     *
     * @return WP_REST_Response
     */
    public function getDebugLogDownloadUrl()
    {
        try {
            $latest_info = $this->getLatestDebugLogInfo();

            if (!$latest_info) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'No debug log copies found in uploads folder',
                    'data' => ['url' => null, 'filename' => null],
                ], 404);
            }

            return new WP_REST_Response(['success' => true, 'data' => $latest_info], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting debug log download URL - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get download URL: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Download latest debug log file directly
     *
     * @return void|WP_REST_Response
     */
    public function downloadLatestDebugLog()
    {
        try {
            $latest_info = $this->getLatestDebugLogInfo();

            if (!$latest_info || !file_exists($latest_info['path'])) {
                return new WP_REST_Response(['success' => false, 'message' => 'No debug log file found'], 404);
            }

            header('Content-Type: text/plain');
            header('Content-Disposition: attachment; filename="' . $latest_info['filename'] . '"');
            header('Content-Length: ' . $latest_info['size']);
            header('Cache-Control: no-cache, must-revalidate');
            header('Pragma: no-cache');

            readfile($latest_info['path']);
            exit;
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error downloading latest debug log - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to download debug log: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get info about the latest debug log file in uploads
     *
     * @return array|null
     */
    public function getLatestDebugLogInfo()
    {
        try {
            $upload_dir = \wp_upload_dir();
            if ($upload_dir['error']) {
                throw new DebugException('Unable to access uploads directory: ' . $upload_dir['error']);
            }

            $pattern = $upload_dir['basedir'] . '/debug-log-*.txt';
            $files = glob($pattern);

            if (empty($files)) {
                return null;
            }

            usort($files, function ($a, $b) {
                return filemtime($b) - filemtime($a);
            });

            $latest_file = $files[0];
            $filename = basename($latest_file);

            return [
                'url' => $upload_dir['baseurl'] . '/' . $filename,
                'filename' => $filename,
                'path' => $latest_file,
                'size' => filesize($latest_file),
                'modified' => filemtime($latest_file),
                'total_copies' => count($files),
            ];
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting latest debug log info - ' . $e->getMessage());
            }
            return null;
        }
    }
}
