<?php
namespace R2_Offload\Media;

defined( 'ABSPATH' ) || exit;

final class Path_Resolver {

	public static function attachment_files( int $attachment_id ): array {
		$file = get_attached_file( $attachment_id );
		if ( ! $file || ! file_exists( $file ) ) {
			return [];
		}

		$files = [ $file ];
		$meta  = wp_get_attachment_metadata( $attachment_id );
		$dir   = trailingslashit( dirname( $file ) );

		if ( is_array( $meta ) && ! empty( $meta['sizes'] ) ) {
			foreach ( $meta['sizes'] as $size ) {
				if ( empty( $size['file'] ) ) {
					continue;
				}
				$candidate = $dir . $size['file'];
				if ( file_exists( $candidate ) ) {
					$files[] = $candidate;
				}
			}
		}

		// Discover sidecar webp/avif variants.
		foreach ( $files as $path ) {
			foreach ( [ '.webp', '.avif' ] as $ext ) {
				$variant = $path . $ext;
				if ( file_exists( $variant ) ) {
					$files[] = $variant;
				}
				$replaced = preg_replace( '/\.(jpe?g|png|gif)$/i', $ext, $path );
				if ( $replaced && $replaced !== $path && file_exists( $replaced ) ) {
					$files[] = $replaced;
				}
			}
		}

		return array_values( array_unique( $files ) );
	}

	/**
	 * Relative object paths (uploads-basedir-relative) derived purely from
	 * attachment metadata — does NOT require the local files to exist. Used for
	 * remote cleanup after local copies were pruned.
	 *
	 * @return string[]
	 */
	public static function relative_paths_from_meta( int $attachment_id, string $basedir ): array {
		$file = get_attached_file( $attachment_id );
		if ( ! $file ) {
			return [];
		}
		$base  = trailingslashit( $basedir );
		$paths = [ $file ];
		$meta  = wp_get_attachment_metadata( $attachment_id );
		$dir   = trailingslashit( dirname( $file ) );

		if ( is_array( $meta ) && ! empty( $meta['sizes'] ) ) {
			foreach ( $meta['sizes'] as $size ) {
				if ( ! empty( $size['file'] ) ) {
					$paths[] = $dir . $size['file'];
				}
			}
		}

		// Include likely sidecar/converted webp/avif variants by name.
		foreach ( $paths as $p ) {
			foreach ( [ '.webp', '.avif' ] as $ext ) {
				$paths[]  = $p . $ext;
				$replaced = preg_replace( '/\.(jpe?g|png|gif)$/i', $ext, $p );
				if ( $replaced && $replaced !== $p ) {
					$paths[] = $replaced;
				}
			}
		}

		$relative = [];
		foreach ( array_unique( $paths ) as $p ) {
			$relative[] = ltrim( str_replace( $base, '', $p ), '/' );
		}
		return array_values( array_unique( $relative ) );
	}
}
