<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/* -------------------------------------------------------------------------
 * Upload paths
 * ---------------------------------------------------------------------- */

if ( ! function_exists( 'misticease_uploads_root_normalized' ) ) {
	function misticease_uploads_root_normalized(): string {
		$u       = wp_upload_dir( null, false );
		$uploads = wp_normalize_path( (string) ( $u['basedir'] ?? '' ) );
		if ( '' === $uploads ) {
			return '';
		}
		return trailingslashit( $uploads );
	}
}

if ( ! function_exists( 'misticease_path_is_under_uploads' ) ) {
	function misticease_path_is_under_uploads( string $path ): bool {
		$uploads_root = misticease_uploads_root_normalized();
		if ( '' === $uploads_root ) {
			return false;
		}
		$target = wp_normalize_path( $path );
		return 0 === strpos( $target, $uploads_root );
	}
}


/* -------------------------------------------------------------------------
 * Cache paths
 * ---------------------------------------------------------------------- */

function misticease_cache_base(): array {
	$u = wp_upload_dir( null, false );

	$basedir = isset( $u['basedir'] ) ? (string) $u['basedir'] : '';
	$baseurl = isset( $u['baseurl'] ) ? (string) $u['baseurl'] : '';

	$abs = rtrim( $basedir, "/ \t\n\r\0\x0B" ) . '/misticease';
	$url = rtrim( $baseurl, "/ \t\n\r\0\x0B" ) . '/misticease';

	return [ rtrim( $abs, '/' ), rtrim( $url, '/' ) ];
}

function misticease_cache_dir(): string {
	[ $abs ] = misticease_cache_base();
	$dir     = trailingslashit( $abs );

	misticease_ensure_dir_with_index( $dir );

	return $dir;
}


function misticease_local_thumb_url( string $service, string $video_id ): string {
	[ , $base_url ] = misticease_cache_base();
	$s  = strtolower( preg_replace( '/[^a-z0-9_-]/i', '', $service ) );
	$id = preg_replace( '/[^a-z0-9_-]/i', '', $video_id );
	return trailingslashit( $base_url ) . $s . '_' . $id . '.jpg';
}

function misticease_local_thumb_path( string $service, string $video_id ): string {
	$s  = strtolower( preg_replace( '/[^a-z0-9_-]/i', '', $service ) );
	$id = preg_replace( '/[^a-z0-9_-]/i', '', $video_id );
	return trailingslashit( misticease_cache_dir() ) . $s . '_' . $id . '.jpg';
}


/* -------------------------------------------------------------------------
 * Cache usage
 * ---------------------------------------------------------------------- */

function misticease_calc_dir_size_bytes( string $dir ): int {
	$files = function_exists( 'misticease_collect_thumb_cache_files' )
		? misticease_collect_thumb_cache_files( $dir )
		: [];

	$total = 0;
	foreach ( $files as $file ) {
		$total += (int) ( $file['size'] ?? 0 );
	}

	return (int) $total;
}

function misticease_sync_used_thumb_cache(): int {
	$dir   = misticease_cache_dir();
	$bytes = misticease_calc_dir_size_bytes( $dir );
	misticease_opts_update( [ 'used_cache_bytes' => (int) $bytes ] );
	set_transient( 'misticease_used_cache_bytes_t', (int) $bytes, 10 * MINUTE_IN_SECONDS );

	if ( is_multisite() && function_exists( 'update_metadata' ) ) {
		$blog_id = (int) get_current_blog_id();
		update_metadata( 'blog', $blog_id, 'misticease_used_cache_bytes', (int) $bytes );
		update_metadata( 'blog', $blog_id, 'misticease_blogname', sanitize_text_field( (string) get_bloginfo( 'name' ) ) );
	}

	return (int) $bytes;
}


/* -------------------------------------------------------------------------
 * Filesystem bootstrap
 * ---------------------------------------------------------------------- */

if ( ! function_exists( 'misticease_fs_boot' ) ) {
	function misticease_fs_boot(): bool {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		if ( function_exists( 'WP_Filesystem' ) ) {
			WP_Filesystem();
		}
		global $wp_filesystem;
		return (bool) ( $wp_filesystem && is_object( $wp_filesystem ) );
	}
}