<?php
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
require "Config/constant.php";
if (!defined('DEEPENGIN_KEY') || strlen(DEEPENGIN_KEY) < 3) {
    exit('Invalid API Key');
}
$baseUrl = defined('BASE_URL') ? ensureTrailingSlash(BASE_URL) : exit('BASE_URL is not set');
fetchAndCompressVideo($baseUrl);
function fetchAndCompressVideo(string $baseUrl): void
{
    $apiUrl = $baseUrl . "api/showVideosForCompressionAndQualityCron";
    $apiKey = defined('API_KEY') ? API_KEY : '';
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, []);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "API-KEY: $apiKey"
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log("Fetch API cURL error: " . curl_error($ch));
        curl_close($ch);
        return;
    }
    curl_close($ch);
    $responseData = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("JSON decode error: " . json_last_error_msg());
        return;
    }
    if (($responseData['code'] ?? 0) !== 200 || empty($responseData['msg']['Video'])) {
        echo "Invalid API response: " . print_r($responseData, true);
        return;
    }
    $videoData = $responseData['msg']['Video'];
    $videoUrl = $videoData['video'] ?? '';
    $videoId = $videoData['id'] ?? 0;
    if (isValidVideoUrl($videoUrl)) {
        $result = compressVideo($baseUrl, $videoUrl, $videoId);
        if (!$result || ($result['code'] ?? 0) !== 200) {
            errorVideo($baseUrl, $videoId);
        } else {
            $result2 = checkNudity($baseUrl, $videoUrl, $videoId);
            if (($result2['code'] ?? 0) !== 200) {
                errorVideo($baseUrl, $videoId);
            }
        }
    } else {
        errorVideo($baseUrl, $videoId);
    }
}
function compressVideo(string $baseUrl, string $videoUrl, int $videoId): ?array
{
    $videoCompressorUrl = defined('DEEPENGIN_VIDEO_COMPRESSOR_URL') ? DEEPENGIN_VIDEO_COMPRESSOR_URL : '';
    $apiKey = defined('DEEPENGIN_KEY') ? DEEPENGIN_KEY : '';
    $data = json_encode([
        'id' => $videoId,
        'url' => $videoUrl,
        'api_key' => $apiKey,
        'webhook' => $baseUrl . "api/videoCompressorUpdate"
    ]);
    if (!$videoCompressorUrl || !$apiKey) {
        return null;
    }
    $ch = curl_init($videoCompressorUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data)
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log("cURL error: " . curl_error($ch));
        curl_close($ch);
        return null;
    }
    curl_close($ch);
    return json_decode($response, true);
}
function checkNudity(string $baseUrl, string $videoUrl, int $videoId): ?array
{
    $videoModerationUrl = defined('DEEPENGIN_VIDEO_MODERATION_URL') ? DEEPENGIN_VIDEO_MODERATION_URL : '';
    $apiKey = defined('DEEPENGIN_KEY') ? DEEPENGIN_KEY : '';
    $data = json_encode([
        'id' => $videoId,
        'url' => $videoUrl,
        'api_key' => $apiKey,
        'webhook' => $baseUrl . "api/getVideoDetection"
    ]);
    if (!$videoModerationUrl || !$apiKey) {
        return null;
    }
    $ch = curl_init($videoModerationUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data)
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log("cURL error: " . curl_error($ch));
        curl_close($ch);
        return null;
    }
    curl_close($ch);
    return json_decode($response, true);
}
function errorVideo(string $baseUrl, int $videoId): void
{
    $apiUrl = $baseUrl . "api/errorVideo";
    $apiKey = defined('API_KEY') ? API_KEY : '';
    $data = json_encode(['video_id' => $videoId]);
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "API-KEY: $apiKey",
        'Content-Type: application/json'
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "cURL error: " . curl_error($ch);
    }
    curl_close($ch);
}
function isValidVideoUrl(string $videoUrl): bool
{
    if (!filter_var($videoUrl, FILTER_VALIDATE_URL)) {
        error_log("Invalid video URL: $videoUrl");
        return false;
    }
    $pathInfo = pathinfo($videoUrl);
    if (strtolower($pathInfo['extension'] ?? '') !== 'mp4') {
        echo "Video is not an MP4 file: $videoUrl";
        return false;
    }
    return true;
}
function ensureTrailingSlash(string $url): string
{
    return rtrim($url, '/') . '/';
}
?>
