#!/usr/bin/env php
<?php
use Index\{UriBase64,XNumber};
use Misuzu\Storage\Files\FileInfoGetFileField;

require_once __DIR__ . '/../misuzu.php';

$options = getopt('hsuv:', [
    'hash',
    'base62',
    'upload',
    'variant:',
], $restIndex);

if($argc <= $restIndex)
    die(sprintf('No file ID specified.%s', PHP_EOL));

$fileId = $argv[$restIndex];
$fileField = FileInfoGetFileField::Id;
$uploadId = null;

$isHash = isset($options['h']) || isset($options['hash']);
$isBase62 = isset($options['s']) || isset($options['base62']);
$isUploadId = isset($options['u']) || isset($options['upload']);
$variant = $options['variant'] ?? $options['v'] ?? '';

if($isHash) {
    $fileId = match(strlen($fileId)) {
        32 => $fileId,
        43 => UriBase64::decode($fileId),
        64 => hex2bin($fileId),
        66 => hex2bin(substr($fileId, 2)),
        default => null,
    };
    $fileField = FileInfoGetFileField::Hash;
} else {
    if($isBase62)
        $fileId = XNumber::fromBase62($fileId);

    if($isUploadId) {
        $uploadId = $fileId;
        $fileId = null;

        try {
            $variantInfo = $msz->storageCtx->uploadsCtx->uploads->getUploadVariant($uploadId, $variant);
        } catch(RuntimeException $ex) {
            $hint = $isBase62 ? 'trim last four characters from base62 id' : 'specify -s for base62 ids';
            die(sprintf('The requested upload variant does not exist. (hint: %s)%s', $hint, PHP_EOL));
        }

        $fileId = $variantInfo->fileId;
    }
}

if($fileId === null)
    die(sprintf('Could not resolve file ID from the provided inputs.%s', PHP_EOL));

try {
    $fileInfo = $msz->storageCtx->filesCtx->data->getFile($fileId, $fileField);
} catch(RuntimeException $ex) {
    $hint = $isUploadId ? (
        $isBase62 ? 'trim last four characters from base62 id' : 'specify -s for base62 ids'
    ) : 'specify -h for hashes or -u to use upload ids, with -v for variant selection';
    die(sprintf('The requested file does not exist. (hint: %s)%s', $hint, PHP_EOL));
}

printf(
    'Found file #%d of %d bytes with type %s at %s with SHA256 hash %s.%s',
    $fileInfo->id,
    $fileInfo->size,
    htmlspecialchars($fileInfo->type),
    $fileInfo->createdAt->toIso8601ZuluString(),
    UriBase64::encode($fileInfo->hash),
    PHP_EOL
);

try {
    printf('Attempting to delete file...%s', PHP_EOL);
    $msz->storageCtx->filesCtx->deleteFile($fileInfo);
} catch(Exception $ex) {
    printf('Exception occurred while deleting file:%s', PHP_EOL);
    printf('%s%s', $ex->getMessage(), PHP_EOL);
}