<?php
namespace FlysystemOffload\Helpers;

class PathHelper
{
    public static function normalizePrefix(string $prefix): string
    {
        $prefix = trim($prefix);
        $prefix = trim($prefix, '/');

        return $prefix ? $prefix . '/' : '';
    }

    public static function stripProtocol(string $path): string
    {
        $path = preg_replace('#^(fly://|https?://[^/]+/uploads/?)#', '', $path);

        return ltrim($path, '/');
    }

    public static function ensureFlyProtocol(string $path): string
    {
        if (str_starts_with($path, 'fly://')) {
            return $path;
        }

        $relative = self::stripProtocol($path);

        return 'fly://' . $relative;
    }

    public static function collectFilesFromAttachment(int $postId): array
    {
        $files = [];

        if ($mainFile = get_attached_file($postId, true)) {
            $files[] = self::stripProtocol($mainFile);
        }

        $metadata = wp_get_attachment_metadata($postId) ?: [];
        $dir = isset($metadata['file']) ? dirname(self::stripProtocol($metadata['file'])) : '';

        if (!empty($metadata['sizes'])) {
            foreach ($metadata['sizes'] as $size) {
                if (!empty($size['file'])) {
                    $files[] = trailingslashit($dir) . ltrim($size['file'], '/');
                }
            }
        }

        $backupSizes = get_post_meta($postId, '_wp_attachment_backup_sizes', true) ?: [];
        foreach ($backupSizes as $size) {
            if (!empty($size['file'])) {
                $files[] = trailingslashit($dir) . ltrim($size['file'], '/');
            }
        }

        return array_unique(array_filter($files));
    }
}
