using UnityEngine;
using HyperstoneSdk;

/// <summary>
/// Example Hyperstone integration demonstrating initialization, configuration consumption,
/// ad revenue tracking (ILRD), in-app purchase tracking, and custom events.
///
/// Attach this MonoBehaviour to a GameObject in your first scene.
/// </summary>
public class ExampleHyperstoneIntegration : MonoBehaviour
{
    // ──────────────────────────────────────────────
    //  Initialization
    // ──────────────────────────────────────────────

    void Start()
    {
        // 1. Subscribe to config changes.
        //    You can call WatchConfig before Initialize — the callback will
        //    fire as soon as a config becomes available.
        Hyperstone.WatchConfig(OnConfigChanged);

        // 2. Initialize the SDK with your credentials from the Hyperstone Console.
        Hyperstone.Initialize("YOUR_APP_ID", "YOUR_APP_SECRET");

        // Optional: set verbose logging during development
        Hyperstone.LogLevel = HyperstoneClient.LogLevel.Debug;
    }

    // ──────────────────────────────────────────────
    //  Receiving Configuration
    // ──────────────────────────────────────────────
    void OnConfigChanged(HyperstoneConfig config)
    {
        Debug.Log($"[Example] Config received: {config}");

        // Read individual values with safe defaults.
        // Keys and their value types are defined in the Hyperstone Console.
        int lives = config.GetIntOrDefault("n_lives", 3);
        bool showAdsAfterDeath = config.GetBoolOrDefault("show_ads_after_death", true);
        float difficultyMultiplier = config.GetFloatOrDefault("difficulty_multiplier", 1.0f);
        string skinId = config.GetStringOrDefault("default_skin", "classic");

        Debug.Log($"[Example] lives={lives}, showAds={showAdsAfterDeath}, " +
                  $"difficulty={difficultyMultiplier}, skin={skinId}");

        // TODO: Apply config values to your game systems
    }

    // ──────────────────────────────────────────────
    //  Ad Revenue Tracking (ILRD)
    // ──────────────────────────────────────────────

    /// <summary>
    /// Call this from your ad callback when a rewarded/interstitial ad is shown.
    /// </summary>
    public void OnAdImpression(string adNetwork, string adFormat, double revenueUsd)
    {
        Hyperstone.LogAdImpression(
            adPlatform: "admob",        // The mediation platform you use
            adNetwork:  adNetwork,      // Actual network that served the ad (e.g. "meta", "unity")
            adFormat:   adFormat,       // "rewarded", "interstitial", "banner", etc.
            revenueUsd: revenueUsd      // Estimated revenue in USD
        );
    }

    /// <summary>
    /// Call this when an ad request is made.
    /// </summary>
    public void OnAdRequested(string adFormat)
    {
        Hyperstone.LogAdRequest(
            adPlatform: "admob",
            adFormat:   adFormat
        );
    }

    /// <summary>
    /// Call this when an ad fails to load or display.
    /// </summary>
    public void OnAdFailed(string adNetwork, string adFormat, string reason)
    {
        Hyperstone.LogAdError(
            adPlatform: "admob",
            adNetwork:  adNetwork,
            adFormat:   adFormat,
            failReason: reason
        );
    }

    // ──────────────────────────────────────────────
    //  In-App Purchases
    // ──────────────────────────────────────────────

    /// <summary>
    /// Call this after a successful IAP transaction.
    /// </summary>
    public void OnPurchaseCompleted(string productId, string currency, double price)
    {
        Hyperstone.LogIapTransactionSuccess(
            productId: productId,
            currency:  currency,
            price:     price
        );
    }

    /// <summary>
    /// Call this when an IAP transaction fails or is cancelled.
    /// </summary>
    public void OnPurchaseFailed(string productId, string reason)
    {
        Hyperstone.LogIapTransactionError(
            productId: productId,
            failReason: reason
        );
    }

    // ──────────────────────────────────────────────
    //  Custom Events & Metrics
    // ──────────────────────────────────────────────

    /// <summary>
    /// Track a gameplay event (e.g. level completion).
    /// </summary>
    public void OnLevelCompleted(int levelNumber, string difficulty)
    {
        Hyperstone.LogCustomEvent("level_completed",
            new Label("level", levelNumber.ToString()),
            new Label("difficulty", difficulty)
        );
    }

    /// <summary>
    /// Track a numeric metric (e.g. in-game currency spent).
    /// </summary>
    public void OnCoinsSpent(int amount, string itemCategory)
    {
        Hyperstone.IncrementCustomMetric("coins_spent", amount,
            new Label("category", itemCategory)
        );
    }

    // ──────────────────────────────────────────────
    //  Cleanup
    // ──────────────────────────────────────────────

    void OnDestroy()
    {
        // Always unsubscribe to prevent callbacks to destroyed objects.
        Hyperstone.UnwatchConfig(OnConfigChanged);
    }
}
