using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace ViKPI.Editor
{
    /// <summary>
    /// Store-policy checks that run with every player build. Google Play (User Data policy) and the
    /// App Store (guideline 5.1.1) require a privacy policy that discloses what an SDK collects, so a
    /// configured SDK without one fails the build instead of failing review later.
    /// </summary>
    internal sealed class VikpiBuildValidator : IPreprocessBuildWithReport, IPostprocessBuildWithReport
    {
        internal const string DocsUrl = "https://vikpi.com/legal/sdk";
        /// <summary>A data type only ViKPI's manifest declares; used to find it in the Xcode project.</summary>
        private const string ManifestMarker = "NSPrivacyCollectedDataTypeGameplayContent";

        public int callbackOrder => 0;

        public void OnPreprocessBuild(BuildReport report)
        {
            var problems = Check(VikpiSettings.Load(), out var warnings);
            foreach (var w in warnings) Debug.LogWarning("[ViKPI] " + w);
            if (problems.Length > 0)
                throw new BuildFailedException("[ViKPI] " + string.Join("\n[ViKPI] ", problems) + "\nSee " + DocsUrl);
        }

        /// <summary>Errors block the build; warnings are logged. Also used by the settings window.</summary>
        internal static string[] Check(VikpiSettings s, out string[] warnings)
        {
            warnings = Array.Empty<string>();
            if (s == null) return Array.Empty<string>();
            var key = s.ApiKey?.Trim() ?? "";
            var configured = key.Length > 0;
            if (!configured) return Array.Empty<string>(); // the SDK stays inert without a key
            if (s.AppTargetsChildren)
            {
                warnings = new[] { "\"App Targets Children\" is on: the SDK collects nothing in this build." };
                return Array.Empty<string>();
            }

            var errors = new System.Collections.Generic.List<string>();
            var warns = new System.Collections.Generic.List<string>();
            if (!s.HasValidPrivacyPolicyUrl)
                errors.Add("Set your game's privacy policy URL (https://…) under Project Settings → ViKPI → Privacy. " +
                           "Google Play and the App Store reject apps whose policy does not disclose session recording and analytics SDKs.");
            if (!key.StartsWith("vk_pub_", StringComparison.Ordinal))
                errors.Add("The API key must start with vk_pub_ (a publishable key). Never ship a secret key in a game build.");
            if (s.ConsentMode == VikpiConsentMode.NotRequired)
                warns.Add("Consent Mode is \"Not Required\": players are recorded without being asked. Only do this if your game already " +
                          "obtains consent elsewhere and discloses screen recording; GDPR and store reviewers expect an explicit choice.");
            if (s.AllowRecording && !s.MaskTextInputs)
                warns.Add("Mask Text Inputs is off: anything players type (names, chat, codes) can appear in session videos. " +
                          "Mask those screens with ViKPI/Recording Mask or turn the option back on.");
            warnings = warns.ToArray();
            return errors.ToArray();
        }

        public void OnPostprocessBuild(BuildReport report)
        {
            if (report.summary.platform != BuildTarget.iOS) return;
            var s = VikpiSettings.Load();
            if (s == null || string.IsNullOrWhiteSpace(s.ApiKey) || s.AppTargetsChildren) return;
            var root = report.summary.outputPath;
            if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return;

            var found = Directory.EnumerateFiles(root, "*.xcprivacy", SearchOption.AllDirectories)
                .Any(f => { try { return File.ReadAllText(f).Contains(ManifestMarker); } catch { return false; } });
            if (!found)
                Debug.LogWarning("[ViKPI] The Xcode project has no privacy manifest entries for ViKPI. Copy the declarations from " +
                                 "Assets/ViKPI/Plugins/iOS/PrivacyInfo.xcprivacy into your app's PrivacyInfo.xcprivacy before submitting " +
                                 "(App Store Connect rejects SDK uses of required-reason APIs that are not declared). See " + DocsUrl);
        }
    }
}
