using System;
using Tornado3_2026Election.Domain;

namespace Tornado3_2026Election.Services;

internal static class ScheduleTemplatePolicy
{
    private const double MinimumCutDurationSeconds = 1d;
    public const string SingleRegionLabel = "단일";

    public static double GetMinimumCutDurationSeconds(FormatTemplateDefinition template)
    {
        return GetMinimumCutDurationSeconds(template.RecommendedChannel, template.Name);
    }

    public static double GetMinimumCutDurationSeconds(BroadcastChannel channel, string? templateName)
    {
        return MinimumCutDurationSeconds;
    }

    public static double NormalizeCutDurationSeconds(double durationSeconds, FormatTemplateDefinition template)
    {
        return NormalizeCutDurationSeconds(durationSeconds, template.RecommendedChannel, template.Name);
    }

    public static double NormalizeCutDurationSeconds(
        double durationSeconds,
        BroadcastChannel channel,
        string? templateName)
    {
        if (double.IsNaN(durationSeconds) || double.IsInfinity(durationSeconds))
        {
            return GetMinimumCutDurationSeconds(channel, templateName);
        }

        var minimum = GetMinimumCutDurationSeconds(channel, templateName);
        return Math.Max(minimum, Math.Round(durationSeconds, 1, MidpointRounding.AwayFromZero));
    }

    public static bool UsesSingleRegionOption(FormatTemplateDefinition? template)
    {
        return template is not null &&
            (IsStaticHistoricalTrendFormat(template.Name) || IsTitleFormat(template.Name));
    }

    public static bool IsStaticHistoricalTrendFormat(string? templateName)
    {
        return string.Equals(templateName, "역대시도판세_광역단체장", StringComparison.Ordinal) ||
            string.Equals(templateName, "역대시도판세_기초단체장", StringComparison.Ordinal);
    }

    public static bool IsTitleFormat(string? templateName)
    {
        return !string.IsNullOrWhiteSpace(templateName) &&
            templateName.Contains("타이틀", StringComparison.Ordinal);
    }

    public static bool IsHistoricalTurnoutFormat(string? templateName)
    {
        return !string.IsNullOrWhiteSpace(templateName) &&
            templateName.StartsWith("사전_역대투표율", StringComparison.Ordinal);
    }

    public static bool IsHistoricalWinnerFormat(string? templateName)
    {
        return !string.IsNullOrWhiteSpace(templateName) &&
            templateName.StartsWith("사전_역대당선", StringComparison.Ordinal);
    }

    public static bool IsCouncilSeatTableFormat(string? templateName)
    {
        return !string.IsNullOrWhiteSpace(templateName) &&
            (templateName.Contains("광역의원표", StringComparison.Ordinal) ||
             templateName.Contains("기초의원표", StringComparison.Ordinal));
    }
}
