// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename       : Helpers.cs
// Author(s)      : Rebecca Wallander <sakcheen@gmail.com>
//
// Component      : Disk image plugins.
//
// --[ Description ] ----------------------------------------------------------
//
//     Contains helpers for A2R flux images.
//
// --[ License ] --------------------------------------------------------------
//
//     This library is free software; you can redistribute it and/or modify
//     it under the terms of the GNU Lesser General Public License as
//     published by the Free Software Foundation; either version 2.1 of the
//     License, or (at your option) any later version.
//
//     This library is distributed in the hope that it will be useful, but
//     WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//     Lesser General Public License for more details.
//
//     You should have received a copy of the GNU Lesser General Public
//     License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2026 Rebecca Wallander
// ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Aaru.CommonTypes;
using Aaru.CommonTypes.Enums;

namespace Aaru.Images;

[SuppressMessage("ReSharper", "UnusedType.Global")]
public sealed partial class A2R
{
    /// <summary>
    ///     Takes a Head, Track and Sub-Track representation, as well as the <c>MediaType</c>,
    ///     and converts it to the Track representation used by A2R.
    /// </summary>
    /// <param name="head">The head number</param>
    /// <param name="track">The track number</param>
    /// <param name="subTrack">The sub-track number</param>
    /// <param name="mediaType">The media type of the image</param>
    /// <returns>A2R format location</returns>
    static long HeadTrackSubToA2RLocation(uint head, ushort track, byte subTrack, MediaType mediaType)
    {
        if(mediaType == MediaType.Apple32SS) return head + track * 4 + subTrack;

        return head + track * 2;
    }

    /// <summary>
    ///     Takes a Head, Track and Sub-Track representation, as well as the <c>A2rDriveType</c>,
    ///     and converts it to the Track representation used by A2R.
    /// </summary>
    /// <param name="head">The head number</param>
    /// <param name="track">The track number</param>
    /// <param name="subTrack">The sub-track number</param>
    /// <param name="driveType">The drive type enum of the A2R image</param>
    /// <returns>A2R format location</returns>
    static long HeadTrackSubToA2RLocation(uint head, ushort track, byte subTrack, A2rDriveType driveType)
    {
        if(driveType == A2rDriveType.SS_525_40trk_quarterStep) return head + track * 4 + subTrack;

        return head + track * 2;
    }

    /// <summary>
    ///     Takes an A2R location and a <c>MediaType</c>, and converts it to a Head, Track and Sub-Track representation
    ///     used by the internal representation. The <c>MediaType</c> is needed because the track location is different
    ///     for different types of media sources.
    /// </summary>
    /// <param name="location">A2R format location</param>
    /// <param name="mediaType"></param>
    /// <param name="head">The head number</param>
    /// <param name="track">The track number</param>
    /// <param name="subTrack">The sub-track number</param>
    static void A2RLocationToHeadTrackSub(uint     location, MediaType mediaType, out uint head, out ushort track,
                                          out byte subTrack)
    {
        if(mediaType == MediaType.Apple32SS)
        {
            head     = 0;
            track    = (ushort)(location / 4);
            subTrack = (byte)(location   % 4);

            return;
        }

        head     = location % 2;
        track    = (ushort)((location - head) / 2);
        subTrack = 0;
    }

    /// <summary>
    ///     Takes a single number flux (uint length) and converts it to a flux in the
    ///     internal representation format (byte length)
    /// </summary>
    /// <param name="ticks">The <c>uint</c> flux representation</param>
    /// <returns>The <c>byte[]</c> flux representation</returns>
    static byte[] UInt32ToFluxRepresentation(uint ticks)
    {
        uint over = ticks / 255;

        if(over == 0) return [(byte)ticks];

        var expanded = new byte[over + 1];

        Array.Fill(expanded, (byte)255, 0, (int)over);
        expanded[^1] = (byte)(ticks % 255);

        return expanded;
    }

    /// <summary>
    ///     Takes a flux representation in the internal format (byte length) and converts it to
    ///     an array of single number fluxes (uint length)
    /// </summary>
    /// <param name="flux">The <c>byte[]</c> flux representation</param>
    /// <returns>The <c>uint</c> flux representation</returns>
    static List<uint> FluxRepresentationsToUInt32List(IEnumerable<byte> flux)
    {
        List<uint> data = [];
        uint       tick    = 0;

        foreach(byte b in flux)
        {
            if(b == 255)
                tick += 255;
            else
            {
                tick += b;
                data.Add(tick);
            }
        }

        return data;
    }

    /// <summary>
    ///     Converts cumulative index signal times from <paramref name="indexResolution" /> tick units to
    ///     <paramref name="dataResolution" /> tick units. A2R RWCP stores one picoseconds-per-tick for both index and flux
    ///     (the data resolution); index samples from sources with a different index clock must be rescaled.
    /// </summary>
    /// <param name="cumulativeIndexTicks">Cumulative absolute times in index-tick units (same encoding as <see cref="FluxRepresentationsToUInt32List" />).</param>
    /// <param name="indexResolution">Picoseconds per tick for the index stream.</param>
    /// <param name="dataResolution">Picoseconds per tick for the RWCP chunk (flux stream).</param>
    /// <param name="cumulativeDataTicks">Cumulative absolute times in data-tick units.</param>
    /// <returns><see cref="ErrorNumber.NoError" /> or <see cref="ErrorNumber.InvalidArgument" /> if scaling is impossible.</returns>
    static ErrorNumber ScaleCumulativeIndexTicksToDataResolution(List<uint> cumulativeIndexTicks,
                                                                   ulong      indexResolution, ulong dataResolution,
                                                                   out List<uint> cumulativeDataTicks)
    {
        cumulativeDataTicks = new List<uint>();

        if(cumulativeIndexTicks is null || cumulativeIndexTicks.Count == 0) return ErrorNumber.NoError;

        if(dataResolution == 0) return ErrorNumber.InvalidArgument;

        if(indexResolution == dataResolution)
        {
            cumulativeDataTicks.AddRange(cumulativeIndexTicks);

            return ErrorNumber.NoError;
        }

        IEnumerable<ulong> scaledTicks = cumulativeIndexTicks.Select(c => ((ulong)c * indexResolution) / dataResolution);

        if(scaledTicks.Any(scaled => scaled > uint.MaxValue))
            return ErrorNumber.InvalidArgument;

        cumulativeDataTicks = scaledTicks.Select(scaled => (uint)scaled).ToList();

        return ErrorNumber.NoError;
    }

    /// <summary>
    ///     Decodes the internal flux data buffer into per-interval tick lengths (data resolution ticks between transitions).
    /// </summary>
    static List<uint> FluxDataBufferToIntervals(byte[] data)
    {
        List<uint> intervals = new List<uint>();

        if(data is null || data.Length == 0) return intervals;

        List<uint> cumulative = FluxRepresentationsToUInt32List(data);
        uint       previous   = 0;

        foreach(uint c in cumulative)
        {
            intervals.Add(c - previous);
            previous = c;
        }

        return intervals;
    }

    /// <summary>
    ///     Drops <paramref name="trimTicks" /> data ticks from the start of the flux stream and re-encodes the remainder.
    /// </summary>
    static ErrorNumber TrimFluxDataLeadingTicks(byte[] data, uint trimTicks, out byte[] trimmed)
    {
        trimmed = Array.Empty<byte>();

        if(trimTicks == 0)
        {
            if(data is null || data.Length == 0)
                return ErrorNumber.NoError;

            trimmed = new byte[data.Length];
            Array.Copy(data, trimmed, data.Length);

            return ErrorNumber.NoError;
        }

        if(data is null || data.Length == 0) return ErrorNumber.InvalidArgument;

        List<uint> intervals = FluxDataBufferToIntervals(data);

        ulong totalTicks = 0;

        foreach(uint iv in intervals) totalTicks += iv;

        if(trimTicks > totalTicks) return ErrorNumber.InvalidArgument;

        ulong      remaining    = trimTicks;
        List<uint> newIntervals = new List<uint>();

        foreach(uint interval in intervals)
        {
            if(remaining == 0)
            {
                newIntervals.Add(interval);

                continue;
            }

            if(remaining >= (ulong)interval)
            {
                remaining -= interval;

                continue;
            }

            uint part = interval - (uint)remaining;
            remaining = 0;
            newIntervals.Add(part);
        }

        if(newIntervals.Count == 0) return ErrorNumber.InvalidArgument;

        List<byte> encoded = new List<byte>();

        foreach(uint iv in newIntervals) encoded.AddRange(UInt32ToFluxRepresentation(iv));

        trimmed = encoded.ToArray();

        return ErrorNumber.NoError;
    }

    /// <summary>
    ///     Determines if a flux capture is a "timing" capture (~1.25 revolutions) or "xtiming" capture (2.25+ revolutions).
    ///     Per A2R 3.x spec: timing captures are quick flux captures (~1.25 revolutions), xtiming captures are extended
    ///     captures (2.25+ revolutions) used for error correction and analysis.
    ///     This function calculates total capture duration from flux data and resolution to determine capture type.
    ///     Note: The calculation uses total flux transition time, which works across different RPMs (300rpm, 360rpm, etc.)
    ///     as it's based on actual capture duration rather than hardcoded RPM values.
    /// </summary>
    /// <param name="resolution">The resolution of the flux capture in picoseconds per tick</param>
    /// <param name="buffer">The flux data buffer (byte array where each byte represents ticks between flux transitions)</param>
    /// <returns><c>true</c> if "timing" (~1.25 revolutions), <c>false</c> if "xtiming" (2.25+ revolutions)</returns>
    static bool IsCaptureTypeTiming(ulong resolution, byte[] buffer)
    {
        if(buffer is null || buffer.Length == 0) return false;

        // Calculate total capture duration in picoseconds
        // Sum all flux transition intervals (bytes) and multiply by resolution
        long totalDuration = buffer.Sum(static x => (long)x) * (long)resolution;

        // Per A2R spec: timing captures are ~1.25 revolutions
        // At 300rpm: 1 revolution = 200ms = 200,000,000,000 picoseconds
        // 1.25 revolutions = 250ms = 250,000,000,000 picoseconds
        // At 360rpm: 1 revolution = 166.67ms = 166,670,000,000 picoseconds
        // 1.25 revolutions = 208.33ms = 208,330,000,000 picoseconds
        // Using a range that accommodates both 300rpm and 360rpm: ~200-280ms
        // This is more flexible than hardcoding for a specific RPM
        const long timingMin = 200000000000; // 200ms minimum for timing
        const long timingMax = 280000000000; // 280ms maximum for timing

        return totalDuration is > timingMin and < timingMax;
    }
}