using System;
using EventsAppQuest.Core;
using EventsAppQuest.Domain.Models;
using UnityEngine;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Consolida e gera o payload exportável da sessão Quest a partir do outcome, closing, recomendação e proposta.
    /// Mantém tudo em memória; preparado para futura integração web/backend/CRM sem implementar persistência real.
    /// </summary>
    public class QuestSessionExportController : MonoBehaviour
    {
        private QuestPresentationSession _session;
        private Func<string> _getProjectId;

        /// <summary>Payload actual (pode ser null até GeneratePayload).</summary>
        public QuestSessionExportPayload Current => _session?.CurrentExportPayload;

        /// <summary>Liga o controlador à sessão.</summary>
        public void Bind(QuestPresentationSession session)
        {
            _session = session;
        }

        /// <summary>Regista um getter opcional para ProjectId (ex.: () => AppSession.CurrentProject?.Id).</summary>
        public void SetProjectIdGetter(Func<string> getProjectId)
        {
            _getProjectId = getProjectId;
        }

        /// <summary>Gera o payload exportável a partir do estado actual da sessão e actualiza CurrentExportPayload e LastExportTimestamp.</summary>
        public void GeneratePayload()
        {
            if (_session == null) return;
            try
            {
                var outcome = _session.CurrentCommercialOutcome;
                var closing = _session.CurrentClosingState;
                var sessionId = outcome?.SessionId ?? ("Quest_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
                var projectId = _getProjectId != null ? _getProjectId() : null;
                var recommendedId = outcome?.RecommendedProposalId ?? closing?.RecommendedProposalId ?? _session.DecisionSummary?.RecommendedProposalId ?? _session.RecommendationSummary?.RecommendedProposalId ?? _session.Proposal?.Id;
                var selectedId = outcome?.SelectedProposalId ?? _session.Proposal?.Id ?? recommendedId;
                var state = outcome != null ? outcome.FinalDecisionState : _session.LastDecisionState;
                var cta = _session.LastConfirmedCTA ?? (outcome != null && outcome.ClosingCTAChosen ? "PrimaryCTA" : (outcome != null && outcome.SecondaryCTAChosen ? "SecondaryCTA" : null));
                var nextAction = outcome?.SuggestedNextAction ?? closing?.SuggestedNextAction ?? _session.DecisionSummary?.SuggestedNextAction ?? "Apresentar proposta ao cliente";
                var priority = outcome?.FollowUpPriority ?? 0;
                var outcomeSummary = outcome?.OutcomeSummary ?? closing?.ClosingSummary ?? _session.DecisionSummary?.ExecutiveShortSummary ?? "";
                var closingSummary = closing != null ? (closing.ClosingHeadline ?? "") + " " + (closing.ClosingSummary ?? "") : outcomeSummary;

                var guidedViewed = _session.GuidedSteps != null && _session.GuidedSteps.Count > 0
                    ? Math.Min(_session.CurrentGuidedStepIndex + 1, _session.GuidedSteps.Count)
                    : 0;
                var durationSec = _session.SessionStartedAtUtc.HasValue
                    ? (DateTime.UtcNow - _session.SessionStartedAtUtc.Value).TotalSeconds
                    : 0;

                var stats = new QuestSessionInteractionStats
                {
                    GuidedStepsViewed = guidedViewed,
                    HotspotsOpened = _session.HotspotContextOpenCount,
                    ComparisonsOpened = _session.ComparisonOpenCount,
                    ClosingOpened = _session.ClosingOpenCount,
                    CTAConfirmations = _session.CTAConfirmationCount,
                    TotalInteractionCount = guidedViewed + _session.HotspotContextOpenCount + _session.ComparisonOpenCount + _session.ClosingOpenCount + _session.CTAConfirmationCount,
                    EstimatedSessionDurationSeconds = durationSec
                };

                _session.CurrentExportPayload = new QuestSessionExportPayload
                {
                    SessionId = sessionId,
                    ProjectId = projectId ?? "",
                    RecommendedProposalId = recommendedId ?? "",
                    SelectedProposalId = selectedId ?? "",
                    FinalDecisionState = state,
                    ConfirmedCTA = cta ?? "",
                    SuggestedNextAction = nextAction ?? "",
                    FollowUpPriority = priority,
                    OutcomeSummary = (outcomeSummary ?? "").Trim(),
                    ClosingSummary = (closingSummary ?? "").Trim(),
                    InteractionStats = stats,
                    Timestamp = DateTime.UtcNow
                };
                _session.LastExportTimestamp = DateTime.UtcNow;
            }
            catch (Exception)
            {
                // Fallback: não quebrar a apresentação; payload fica null ou anterior
            }
        }

        /// <summary>Limpa o payload actual e o timestamp (regenerar com GeneratePayload).</summary>
        public void ClearPayload()
        {
            if (_session == null) return;
            _session.CurrentExportPayload = null;
            _session.LastExportTimestamp = null;
        }
    }
}
