using System;
using System.Collections.Generic;
using EventsAppQuest.Core;
using UnityEngine;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Consolida o relatório final/handoff da sessão Quest a partir do outcome, export, estatísticas e fechamento.
    /// Mantém tudo em memória; preparado para futura integração web/backend/CRM.
    /// </summary>
    public class QuestSessionHandoffReportController : MonoBehaviour
    {
        private QuestPresentationSession _session;
        private Func<string> _getProjectId;

        /// <summary>Relatório actual (pode ser null até GenerateReport).</summary>
        public QuestSessionHandoffReport Current => _session?.CurrentHandoffReport;

        public void Bind(QuestPresentationSession session)
        {
            _session = session;
        }

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

        /// <summary>Gera ou regenera o relatório de handoff a partir do estado actual da sessão.</summary>
        public void GenerateReport()
        {
            if (_session == null) return;
            try
            {
                var outcome = _session.CurrentCommercialOutcome;
                var export = _session.CurrentExportPayload;
                var stats = export?.InteractionStats;
                var closing = _session.CurrentClosingState;

                var sessionId = outcome?.SessionId ?? export?.SessionId ?? ("Quest_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
                var projectId = _getProjectId != null ? _getProjectId() : null;
                var recommendedId = outcome?.RecommendedProposalId
                                    ?? export?.RecommendedProposalId
                                    ?? _session.DecisionSummary?.RecommendedProposalId
                                    ?? _session.RecommendationSummary?.RecommendedProposalId
                                    ?? _session.Proposal?.Id;
                var selectedId = outcome?.SelectedProposalId ?? export?.SelectedProposalId ?? _session.Proposal?.Id ?? recommendedId;
                var finalState = outcome != null ? outcome.FinalDecisionState : (_session.LastDecisionState != 0 ? _session.LastDecisionState : QuestCommercialDecisionState.ExplorationOnly);
                var confirmedCta = _session.LastConfirmedCTA ?? export?.ConfirmedCTA ?? "";
                var nextAction = outcome?.SuggestedNextAction
                                 ?? export?.SuggestedNextAction
                                 ?? _session.DecisionSummary?.SuggestedNextAction
                                 ?? "Apresentar proposta ao cliente";
                var priority = outcome?.FollowUpPriority ?? export?.FollowUpPriority ?? 0;
                var outcomeSummary = outcome?.OutcomeSummary
                                     ?? export?.OutcomeSummary
                                     ?? _session.DecisionSummary?.ExecutiveShortSummary
                                     ?? "";
                var closingSummary = closing != null
                    ? (closing.ClosingHeadline ?? "") + " " + (closing.ClosingSummary ?? "")
                    : (export?.ClosingSummary ?? outcomeSummary);

                var confidence = outcome?.ConfidenceLevel
                                 ?? closing?.ConfidenceLabel
                                 ?? (_session.RecommendationSummary != null && _session.RecommendationSummary.RecommendationConfidenceScore > 0
                                        ? "Confiança " + _session.RecommendationSummary.RecommendationConfidenceScore + "%"
                                        : "");

                var keyHotspots = new List<string>();
                if (_session.Hotspots != null && _session.Hotspots.Count > 0)
                {
                    foreach (var h in _session.Hotspots)
                    {
                        if (string.IsNullOrEmpty(h.Title) && string.IsNullOrEmpty(h.Description)) continue;
                        keyHotspots.Add(h.Title ?? h.Description);
                        if (keyHotspots.Count >= 3) break;
                    }
                }

                var keyComparisons = new List<string>();
                if (stats != null && stats.ComparisonsOpened > 0)
                {
                    keyComparisons.Add("Comparações de hotspots realizadas (" + stats.ComparisonsOpened + ")");
                }

                _session.CurrentHandoffReport = new QuestSessionHandoffReport
                {
                    SessionId = sessionId ?? "",
                    ProjectId = projectId ?? "",
                    RecommendedProposalId = recommendedId ?? "",
                    SelectedProposalId = selectedId ?? "",
                    FinalDecisionState = finalState,
                    ConfirmedCTA = confirmedCta ?? "",
                    SuggestedNextAction = nextAction?.Trim() ?? "",
                    FollowUpPriority = priority,
                    OutcomeSummary = outcomeSummary?.Trim() ?? "",
                    ClosingSummary = closingSummary?.Trim() ?? "",
                    KeyHotspotsVisited = keyHotspots,
                    KeyComparisonsViewed = keyComparisons,
                    FinalConfidenceLabel = confidence ?? "",
                    HandoffNotes = "",
                    GeneratedAt = DateTime.UtcNow
                };
                _session.LastHandoffGeneratedAt = _session.CurrentHandoffReport.GeneratedAt;
                _session.HasGeneratedHandoffReport = true;
            }
            catch (Exception)
            {
                // Fallback: não quebrar a apresentação; relatório fica null ou anterior
            }
        }

        /// <summary>Limpa o relatório actual e os metadados na sessão.</summary>
        public void ClearReport()
        {
            if (_session == null) return;
            _session.CurrentHandoffReport = null;
            _session.LastHandoffGeneratedAt = null;
            _session.HasGeneratedHandoffReport = false;
        }
    }
}

