<?php

namespace Shopping\Feed;

class FeedCompressor {

    /**
     * Compress a feed file using gzip.
     *
     * @param string $sourcePath Path to final .jsonl file
     * @return string Path to compressed file (.gz)
     *
     * @throws \RuntimeException on failure
     */
    public function compress(string $sourcePath): string {
        if (!file_exists($sourcePath)) {
            throw new \RuntimeException("Feed file not found: {$sourcePath}");
        }

        $gzPath = $sourcePath . '.gz';
        $tmpGzPath = $gzPath . '.tmp';

        $in = fopen($sourcePath, 'rb');
        if (!$in) {
            throw new \RuntimeException("Failed to open feed for compression");
        }

        $out = gzopen($tmpGzPath, 'wb9'); // max compression
        if (!$out) {
            fclose($in);
            throw new \RuntimeException("Failed to open gzip stream");
        }

        while (!feof($in)) {
            gzwrite($out, fread($in, 1024 * 1024)); // 1MB chunks
        }

        fclose($in);
        gzclose($out);

        // Atomic publish
        if (!rename($tmpGzPath, $gzPath)) {
            @unlink($tmpGzPath);
            throw new \RuntimeException("Failed to publish compressed feed");
        }

        return $gzPath;
    }
}