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

namespace EventsAppQuest.Infrastructure.Services
{
    /// <summary>
    /// Gera resumo executivo de decisão a partir da recomendação final, review, fit score e comparações.
    /// </summary>
    public class MockProposalDecisionSummaryService : IProposalDecisionSummaryService
    {
        public ProposalDecisionSummary Generate(EventProject project)
        {
            var result = new ProposalDecisionSummary();
            if (project?.Proposals == null || project.Proposals.Count == 0)
                return result;

            var recommendationService = ServiceRegistry.Instance.Get<IProposalRecommendationService>();
            var rec = project.LastRecommendationSummary;
            if (rec == null && recommendationService != null)
                rec = recommendationService.Recommend(project);
            if (rec == null || string.IsNullOrEmpty(rec.RecommendedProposalId))
            {
                result.DecisionReadinessLevel = ProposalDecisionReadinessLevel.NotReady;
                result.ExecutiveHeadline = "Complete as propostas e gere a recomendação para obter o resumo de decisão.";
                result.SuggestedNextAction = "Gerar recomendação final (duas ou mais propostas e revisão).";
                return result;
            }

            var recommended = project.Proposals.FirstOrDefault(p => p.Id == rec.RecommendedProposalId);
            if (recommended == null)
                return result;

            result.RecommendedProposalId = rec.RecommendedProposalId;
            var recName = recommended.Name ?? "Proposta recomendada";
            var review = recommended.ReviewSummary ?? (recommended.Id == project.ActiveProposalId ? project.LastProposalReviewSummary : null);

            result.ExecutiveHeadline = recName + " é a opção recomendada para fechamento no contexto atual do projeto.";
            result.ExecutiveShortSummary = rec.ExecutiveSummary ?? string.Format("{0} apresenta a melhor aderência ao briefing (score {1}) e está {2}. {3}",
                recName, recommended.FitScore?.OverallScore ?? 0,
                review?.IsReadyForPresentation == true ? "pronta para apresentação" : "em revisão",
                !string.IsNullOrEmpty(rec.BudgetPositioning) ? rec.BudgetPositioning : "");

            result.MainDecisionReasons = rec.WhyItWins != null ? new List<string>(rec.WhyItWins) : new List<string>();
            result.KeyRisks = rec.Tradeoffs != null ? new List<string>(rec.Tradeoffs) : new List<string>();
            result.BudgetConclusion = rec.BudgetPositioning ?? "Revisar orçamento na proposta.";
            result.ExperienceConclusion = rec.ExperiencePositioning ?? "Revisar jornada e evolução visual.";
            result.OperationalConclusion = rec.OperationalPositioning ?? "Revisar fluxo e montagem.";
            result.FinalSalesMessage = rec.SuggestedSalesAngle ?? "Apresentar valor da proposta e aderência ao evento desejado.";

            var hasWarnings = (result.KeyRisks?.Count ?? 0) > 0 || (review?.Warnings?.Count ?? 0) > 0;
            var readyForPresentation = review?.IsReadyForPresentation == true;
            var confidence = rec.RecommendationConfidenceScore;

            if (!readyForPresentation && (review?.MissingElements?.Count ?? 0) > 0)
            {
                result.DecisionReadinessLevel = ProposalDecisionReadinessLevel.UnderReview;
                result.SuggestedNextAction = "Completar elementos ausentes e revisar proposta; em seguida gerar novamente a recomendação.";
            }
            else if (!readyForPresentation || (hasWarnings && confidence < 70))
            {
                result.DecisionReadinessLevel = ProposalDecisionReadinessLevel.UnderReview;
                result.SuggestedNextAction = "Revisar alertas e prontidão da proposta; depois apresentar ao cliente.";
            }
            else if (confidence >= 80 && readyForPresentation && (result.KeyRisks?.Count ?? 0) <= 1)
            {
                result.DecisionReadinessLevel = ProposalDecisionReadinessLevel.ReadyToClose;
                result.SuggestedNextAction = "Apresentar proposta recomendada ao cliente e conduzir ao fechamento.";
            }
            else
            {
                result.DecisionReadinessLevel = ProposalDecisionReadinessLevel.ReadyToPresent;
                result.SuggestedNextAction = "Apresentar proposta recomendada ao cliente; considerar tradeoffs antes de fechar.";
            }

            return result;
        }
    }
}
