using UnityEngine;

namespace ViKPI
{
    /// <summary>How the SDK obtains the player's permission before collecting anything.</summary>
    public enum VikpiConsentMode
    {
        /// <summary>The SDK shows its own short prompt (with your privacy policy link) on first launch.</summary>
        BuiltInPrompt = 0,

        /// <summary>Your game (or consent platform) asks, then calls <see cref="Vikpi.SetConsent"/>.</summary>
        Manual = 1,

        /// <summary>
        /// Collect without asking. Only for games that already have another legal basis and disclose
        /// session recording elsewhere; the build validator warns about it.
        /// </summary>
        NotRequired = 2,
    }

    /// <summary>
    /// Project-wide SDK configuration. Lives in a Resources folder so the runtime can load it
    /// before the first scene. Edit it under Project Settings → ViKPI.
    /// </summary>
    public sealed class VikpiSettings : ScriptableObject
    {
        public const string ResourceName = "VikpiSettings";
        public const string DefaultEndpoint = "https://vikpi.com";

        [Tooltip("Publishable project key (vk_pub_…). Create one in the dashboard under Project settings → API keys.")]
        [SerializeField] private string apiKey = "";

        [Tooltip("Origin of the ViKPI server. Change it only if you self-host.")]
        [SerializeField] private string endpoint = DefaultEndpoint;

        [Tooltip("Start automatically before the first scene loads (once the player has consented). Turn off to call Vikpi.Init() yourself.")]
        [SerializeField] private bool autoStart = true;

        [Tooltip("Also send data from Play Mode in the Editor. Off by default so editor sessions don't mix with players'.")]
        [SerializeField] private bool runInEditor;

        // ---------- privacy ----------

        [Tooltip("Required. Your game's privacy policy (https://…). It must say that gameplay, touches and screen video are recorded with ViKPI. Builds fail without it.")]
        [SerializeField] private string privacyPolicyUrl = "";

        [SerializeField] private VikpiConsentMode consentMode = VikpiConsentMode.BuiltInPrompt;

        [Tooltip("Turn on if your game is directed at children (Google Play Families, Apple Kids category, COPPA). The SDK then collects nothing at all.")]
        [SerializeField] private bool appTargetsChildren;

        [Tooltip("Black out every text input field (InputField, TMP_InputField) in recordings, so typed names, chat or codes never leave the device.")]
        [SerializeField] private bool maskTextInputs = true;

        [SerializeField] private string consentTitle = "Help us improve the game";
        [TextArea(3, 8)]
        [SerializeField] private string consentMessage =
            "With your permission, we record how you play (taps, screens, performance, errors and a short video of the game screen) " +
            "to fix bugs and improve the game. Text you type is never recorded. Nothing is used for advertising. " +
            "You can change your choice at any time in the settings.";
        [SerializeField] private string consentAcceptLabel = "Allow";
        [SerializeField] private string consentDeclineLabel = "Don't allow";
        [SerializeField] private string consentPolicyLabel = "Privacy policy";

        // ---------- collection ----------

        [SerializeField] private bool trackTouches = true;
        [SerializeField] private bool trackPerformance = true;
        [SerializeField] private bool captureErrors = true;

        [Tooltip("Allow video recording. The sample rate, frame rate and quality are set per project in the dashboard.")]
        [SerializeField] private bool allowRecording = true;

        [Tooltip("A new session starts when the app returns from the background after this long.")]
        [Min(30)]
        [SerializeField] private int sessionTimeoutSeconds = 300;

        [Tooltip("Unsent data kept on the device while offline. Video is dropped first when full.")]
        [Min(5)]
        [SerializeField] private int maxOfflineStorageMb = 50;

        [SerializeField] private bool debugLogging;

        public string ApiKey { get => apiKey; set => apiKey = value; }
        public string Endpoint { get => endpoint; set => endpoint = value; }
        public bool AutoStart { get => autoStart; set => autoStart = value; }
        public bool RunInEditor { get => runInEditor; set => runInEditor = value; }
        public string PrivacyPolicyUrl { get => privacyPolicyUrl; set => privacyPolicyUrl = value; }
        public VikpiConsentMode ConsentMode { get => consentMode; set => consentMode = value; }
        public bool AppTargetsChildren { get => appTargetsChildren; set => appTargetsChildren = value; }
        public bool MaskTextInputs { get => maskTextInputs; set => maskTextInputs = value; }
        public string ConsentTitle { get => consentTitle; set => consentTitle = value; }
        public string ConsentMessage { get => consentMessage; set => consentMessage = value; }
        public string ConsentAcceptLabel { get => consentAcceptLabel; set => consentAcceptLabel = value; }
        public string ConsentDeclineLabel { get => consentDeclineLabel; set => consentDeclineLabel = value; }
        public string ConsentPolicyLabel { get => consentPolicyLabel; set => consentPolicyLabel = value; }
        public bool TrackTouches { get => trackTouches; set => trackTouches = value; }
        public bool TrackPerformance { get => trackPerformance; set => trackPerformance = value; }
        public bool CaptureErrors { get => captureErrors; set => captureErrors = value; }
        public bool AllowRecording { get => allowRecording; set => allowRecording = value; }
        public int SessionTimeoutSeconds { get => sessionTimeoutSeconds; set => sessionTimeoutSeconds = Mathf.Max(30, value); }
        public int MaxOfflineStorageMb { get => maxOfflineStorageMb; set => maxOfflineStorageMb = Mathf.Max(5, value); }
        public bool DebugLogging { get => debugLogging; set => debugLogging = value; }

        /// <summary>True when <see cref="PrivacyPolicyUrl"/> is an absolute https URL.</summary>
        public bool HasValidPrivacyPolicyUrl => IsValidPolicyUrl(privacyPolicyUrl);

        public static bool IsValidPolicyUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return false;
            return System.Uri.TryCreate(url.Trim(), System.UriKind.Absolute, out var u)
                   && u.Scheme == "https" && !string.IsNullOrEmpty(u.Host) && u.Host.Contains(".");
        }

        public static VikpiSettings Load() => Resources.Load<VikpiSettings>(ResourceName);

        /// <summary>Settings for code-only setups, without an asset.</summary>
        public static VikpiSettings CreateDefault() => CreateInstance<VikpiSettings>();
    }
}
