<?php
use Magento\Framework\App\Bootstrap;
use Magento\Framework\File\Csv;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$csv = $objectManager->get(Csv::class);
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');

$inputFile = __DIR__ . '/' . 'GV_Only_Additional_Images.csv';
$outputFile = __DIR__ . '/' . 'processed_images.csv';
$credentialsFile = __DIR__ . '/pub/media/importexport/a/u/autogedal-340216-786dbe024fc8_1.json';
$batchSize = 10;

$client = new \Google_Client();
$client->setAuthConfig($credentialsFile);
$client->setScopes(\Google_Service_Drive::DRIVE_READONLY);
$googleService = new \Google_Service_Drive($client);

function getFileNameFromDrive($link, $googleService) {
    preg_match('/(?:\/d\/|[?&]id=)([\w-]+)/', $link, $matches);
    $linkId = $matches[1] ?? '';

    if (!$linkId) {
        preg_match('/^([\w-]{25,})/', $link, $matches);
        $linkId = $matches[1] ?? '';
    }

    if (!$linkId) {
        return '';
    }

    try {
        $fileInfo = $googleService->files->get($linkId);
        $name = $fileInfo->getName();

        if (!pathinfo($name, PATHINFO_EXTENSION)) {
            $extension = $fileInfo->getFileExtension();
            $name .= '.' . $extension;
        }

        return $name;
    } catch (\Exception $e) {
        echo "Error getting file info for ID {$linkId}: " . $e->getMessage() . "\n";
        return '';
    }
}

try {
    $inputHandle = fopen($inputFile, 'r');
    $outputHandle = fopen($outputFile, 'w');

    $header = fgetcsv($inputHandle);
    fputcsv($outputHandle, $header);

    $batch = [];
    $totalProcessed = 0;
    $batchCount = 0;

    while (($row = fgetcsv($inputHandle)) !== false) {
        $sku = $row[0];
        $imageLinks = explode('|', $row[1]);
        $processedImages = [];

        echo "Processing SKU: $sku\n";

        foreach ($imageLinks as $link) {
            $fileName = getFileNameFromDrive($link, $googleService);
            if ($fileName) {
                $processedImages[] = 'pub/media/import/' . $fileName;
            }
        }

        $batch[] = [
            $sku,
            implode('|', $processedImages)
        ];

        $totalProcessed++;

        if (count($batch) >= $batchSize) {
            $batchCount++;
            foreach ($batch as $batchRow) {
                fputcsv($outputHandle, $batchRow);
            }

            echo "Wrote batch {$batchCount} ({$totalProcessed} rows processed)\n";
            $batch = [];
        }
    }

    if (!empty($batch)) {
        $batchCount++;
        foreach ($batch as $batchRow) {
            fputcsv($outputHandle, $batchRow);
        }

        echo "Wrote final batch {$batchCount} ({$totalProcessed} total rows processed)\n";
    }

    fclose($inputHandle);
    fclose($outputHandle);

    echo "Process completed successfully. Output file: $outputFile\n";
    echo "Total rows processed: {$totalProcessed}\n";
    echo "Total batches: {$batchCount}\n";

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    if (isset($inputHandle) && is_resource($inputHandle)) {
        fclose($inputHandle);
    }
    if (isset($outputHandle) && is_resource($outputHandle)) {
        fclose($outputHandle);
    }
}