#! /usr/bin/env php
<?php

/**
 * Script to rescore logs that were scored with an older version of Logchecker.
 *
 * Usage: rescore-logs [--dry-run] [--include-adjusted] [--limit <n>] [--offset <n>]
 */

namespace Gazelle;

use OrpheusNET\Logchecker\Logchecker;

require __DIR__ . '/../lib/bootstrap.php';

$includeAdjusted = in_array('--include-adjusted', $argv);

$limitKey = array_find_key($argv, fn ($val) => $val === '--limit');
if ($limitKey !== null) {
    if (!isset($argv[$limitKey + 1]) || !is_numeric($argv[$limitKey + 1])) {
        die("If you specify --limit, you must also provide a numeric limit\n");
    }
    $limit = (int)$argv[$limitKey + 1];
} else {
    $limit = PHP_INT_MAX;
}

$offsetKey = array_find_key($argv, fn ($val) => $val === '--offset');
if ($offsetKey !== null) {
    if (!isset($argv[$offsetKey + 1]) || !is_numeric($argv[$offsetKey + 1])) {
        die("If you specify --offset, you must also provide a numeric offset\n");
    }
    $offset = (int)$argv[$offsetKey + 1];
} else {
    $offset = 0;
}

$logcheckerVersion = Logchecker::getLogcheckerVersion();
[$major, $minor, $patch] = explode('.', $logcheckerVersion);

$extra = '';
$args = [$major, $major, $minor, $major, $minor, $patch];

$db = DB::DB();

if (!$includeAdjusted) {
    $extra = 'AND Adjusted = ?';
    $args[] = '0';
}

$args[] = $limit;
$args[] = $offset;

$db->prepared_query("
    SELECT tl.TorrentID, tl.LogID, tl.Score
    FROM torrents_logs AS tl
    INNER JOIN torrents AS t ON (t.ID = tl.TorrentID)
    WHERE
        (
            LogcheckerVersion = ''
            OR CAST(SUBSTRING_INDEX(LogcheckerVersion, '.', 1) AS UNSIGNED) < ?
            OR (
                CAST(SUBSTRING_INDEX(LogcheckerVersion, '.', 1) AS UNSIGNED) = ? AND
                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(LogcheckerVersion, '.', 2), '.', -1) AS UNSIGNED) < ?
            )
            OR (
                CAST(SUBSTRING_INDEX(LogcheckerVersion, '.', 1) AS UNSIGNED) = ? AND
                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(LogcheckerVersion, '.', 2), '.', -1) AS UNSIGNED) = ? AND
                CAST(SUBSTRING_INDEX(LogcheckerVersion, '.', -1) AS UNSIGNED) < ?
            )
        )
        {$extra}
    ORDER BY LogID, TorrentID
    LIMIT ? OFFSET ?
", ...$args);

$riplogMan = new Manager\Riplog();
$torMan    = new Manager\Torrent();

/** @var Torrent|null */
$torrent = null;
$i       = 0;
while (true) {
    $db->set_query_id($queryId);
    $row = $db->next_row(MYSQLI_NUM);
    if (!$row) {
        break;
    }

    [$torrentId, $logId, $score] = $row;

    if ($torrent->id !== $torrentId) {
        if ($torrent) {
            $riplogMan->refreshTorrent($torrent);
        }
        $torrent = $torMan->findById($torrentId);
        if (!$torrent) {
            continue;
        }
    }

    $logpath = new File\RipLog($torrent->id, $logId)->path();
    $riplog = $riplogMan->create($torrent, $logpath, basename($logpath));

    printf(
        "%d: torrent %d - log %d (%s): %d -> %d\n",
        $i++,
        $torrent->id,
        $logId,
        $logpath,
        $score,
        $riplog->score()
    );
}

if ($torrent) {
    $riplogMan->refreshTorrent($torrent);
}
