using System.Collections.Generic;
using System.Linq;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Enums;
using EventsAppQuest.Domain.Models;
using UnityEngine;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Prepara automaticamente dados mock suficientes para rodar um vertical slice curto no Quest,
    /// abrindo direto `QuestPresentation` sem depender do fluxo completo do CRM.
    /// </summary>
    public static class QuestAndroidVerticalSliceSeeder
    {
        public const string PrefsAutoRunKey = "EAQ_QUEST_VERTICAL_SLICE_AUTORUN";

        public static bool IsQuestAndroidBuild()
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            return true;
#else
            return false;
#endif
        }

        public static bool ShouldSeedForVerticalSlice()
        {
            // Android/Quest: seed + demo automático (demo é controlado no QuestPresentationController).
            if (IsQuestAndroidBuild()) return true;

            // Windows/Editor: seed para que o fluxo funcione para validação manual.
            try
            {
                return Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer;
            }
            catch
            {
                return false;
            }
        }

        public static bool ShouldAutoRunDemo()
        {
            try
            {
                return PlayerPrefs.GetInt(PrefsAutoRunKey, 1) == 1;
            }
            catch
            {
                return true;
            }
        }

        public static void TryEnsureSeed(AppSession session)
        {
            if (session == null) return;
            if (!ShouldSeedForVerticalSlice()) return;

            var project = session.CurrentProject;
            var activeProposal = project?.GetActiveProposal();

            // Já tem dados suficientes? Não reseed.
            if (activeProposal != null
                && activeProposal.MRPresentationPlan != null
                && (activeProposal.GuidedTourSteps?.Count ?? 0) > 0
                && (activeProposal.VisualHotspots?.Count ?? 0) > 1
                && (activeProposal.SceneStates?.Count ?? 0) > 0)
            {
                return;
            }

            var registry = ServiceRegistry.Instance;
            var categoryService = registry.Get<IEventCategoryService>();
            var spaceService = registry.Get<ISpaceService>();
            var templateService = registry.Get<ITemplateService>();
            var showroomService = registry.Get<IShowroomService>();
            var supplierService = registry.Get<ISupplierService>();
            var themeService = registry.Get<IVisualThemeService>();
            var packageService = registry.Get<ICommercialPackageService>();
            var recommendationService = registry.Get<IProposalRecommendationService>();
            var decisionService = registry.Get<IProposalDecisionSummaryService>();

            if (categoryService == null || spaceService == null || templateService == null
                || showroomService == null || supplierService == null || themeService == null || packageService == null
                || recommendationService == null || decisionService == null)
            {
                return;
            }

            var category = categoryService.GetAll()?.FirstOrDefault();
            var space = spaceService.GetAll()?.FirstOrDefault();
            if (category == null || space == null) return;

            var templates = templateService.GetByCategoryId(category.Id);
            var template = (templates != null && templates.Count > 0) ? templates.FirstOrDefault() : templateService.GetAll().FirstOrDefault();
            if (template == null) return;

            // Pré-seleção de fornecedores para influenciar pricing/review (mock).
            var suppliers = supplierService.GetAll()?.ToList() ?? new List<Supplier>();

            session.SelectedCategory = category;
            session.SelectedSpace = space;
            session.SelectedTemplate = template;

            session.ClearSupplierSelection();
            if (suppliers.Count > 0) session.ToggleSupplierSelection(suppliers[0].Id);
            if (suppliers.Count > 1) session.ToggleSupplierSelection(suppliers[1].Id);

            session.StartProject("Quest Vertical Slice (Debug)");
            if (session.CurrentProject == null) return;

            // Aplica pacote comercial para garantir itens + tema sugerido.
            var availablePackages = packageService.GetAvailableForProject(session.CurrentProject);
            var package = availablePackages != null && availablePackages.Count > 0 ? availablePackages.FirstOrDefault() : null;
            if (package != null)
            {
                session.ApplyCommercialPackage(package.Id);
            }

            // Seleciona um tema compatível com o projeto.
            var availableThemes = themeService.GetAvailableForProject(session.CurrentProject);
            var preferredTheme = availableThemes?.FirstOrDefault(t => t.IsDefault) ?? availableThemes?.FirstOrDefault();
            if (preferredTheme != null)
                session.ApplyTheme(preferredTheme.Id);

            // Brief realista o suficiente para deixar scoring/review coerentes.
            session.SetClientBrief(new ClientEventBrief
            {
                ClientName = "Cliente Demo",
                EventName = "Evento Demo",
                GuestCount = 60,
                EstimatedBudgetTarget = 7000f,
                PreferredMood = "Premium",
                PreferredColors = new List<string> { "Dourado", "Preto" },
                MustHaveElements = new List<string> { "mesa", "bolo", "decoração" },
                AvoidElements = new List<string>(),
                Notes = "Modo vertical slice Quest: fluxo curto para validação de HUD/painéis e navegação."
            });

            // Gera narrativa + review para preencher guided steps/hotspots/states.
            session.GeneratePresentation();
            session.ReviewProposal();

            // Recomendação + decisão para abrir fechamento.
            session.CurrentProject.LastRecommendationSummary = recommendationService.Recommend(session.CurrentProject);
            session.CurrentProject.LastDecisionSummary = decisionService.Generate(session.CurrentProject);

            if (session.CurrentProject.LastDecisionSummary != null)
            {
                // Garantir que o closing abra no demo (confiabilidade do vertical slice).
                session.CurrentProject.LastDecisionSummary.DecisionReadinessLevel = ProposalDecisionReadinessLevel.ReadyToClose;
                if (string.IsNullOrWhiteSpace(session.CurrentProject.LastDecisionSummary.SuggestedNextAction))
                    session.CurrentProject.LastDecisionSummary.SuggestedNextAction = "Apresentar a proposta ao cliente e concluir o fechamento.";
            }

            // Mantém consistência para BuildSession: recommendation deve apontar para proposal ativa.
            var updatedActive = session.CurrentProject.GetActiveProposal();
            if (updatedActive != null)
            {
                if (session.CurrentProject.LastRecommendationSummary != null)
                    session.CurrentProject.LastRecommendationSummary.RecommendedProposalId = updatedActive.Id;
                if (session.CurrentProject.LastDecisionSummary != null)
                    session.CurrentProject.LastDecisionSummary.RecommendedProposalId = updatedActive.Id;
            }

            session.SyncActiveProposalFromProject();
        }
    }
}

