from __future__ import annotations

import json
from datetime import datetime
from typing import Any, Dict

import langfuse

from agent.base.base_classifier import BaseClassifier


client = langfuse.Langfuse(timeout=30)


class ConversationClassifier(BaseClassifier):
    PROMPT_FILE = "conversation_classifier.txt"
    REASONING_EFFORT = "low"

    def run(self, text: str) -> Dict[str, Any]:
        output = self.chain.invoke(text)
        return json.loads(output.content)


def get_historic_conversation(trace_id):
    trace = client.api.trace.get(trace_id).dict()
    ordered_obs = sorted(
        trace["observations"],
        key=lambda x: x.get("startTime") or ""
    )

    conversation = ""
    for obs in ordered_obs:
        meta = obs.get("metadata", {})
        stage = meta.get("stage")

        if not stage or stage == "check_guardrail":
            continue

        model_msg = obs.get("output")
        human_msg = obs.get("input")

        if isinstance(human_msg, dict):
            human_msg = human_msg.get("text")

        conversation += (
            f"ESTÁGIO:{stage}\n"
            f"HUMANO:{human_msg}\n"
            f"MODELO:{model_msg}\n\n"
        )

    return conversation.strip()


def format_success_purchase(raw_mailing):
    allowed_keys = [
        'NUM_TELEFONE', 'DATA_VENCIMENTO', 'NOME_CLIENTE_COMPLETO',
        'NUM_CPF_CNPJ_CLIENTE', 'ACAO', 'BONUS_DESTINO', 'FLG_FID',
        'USO_DE_DADOS', 'DESCONTO_DESTINO', 'DAT_NASCIMENTO',
        'VALOR_PLANO_CORE', 'VLR_PLANO_DESTINO',
        'VLR_FINAL_PLANO_DEST', 'DADOS_CORE', 'ENDERECO',
        'UF', 'TIPO_MAILING', 'AGING_PLANO'
    ]
    return {k: v for k, v in raw_mailing.items() if k in allowed_keys}


def format_call(raw_mailing, reason_status, summary):
    return {
        "DATA": datetime.now().strftime("%Y-%m-%d"),
        "HORA": datetime.now().strftime("%H:%M:%S"),
        "NUM_ACESSO": raw_mailing["NUM_TELEFONE"],
        "NOME": raw_mailing["NOME_CLIENTE_COMPLETO"],
        "NUM_DOCUMENTO": raw_mailing["NUM_CPF_CNPJ_CLIENTE"],
        "STATUS": "CONTATO",
        "DESC_STATUS": list(reason_status.keys())[0],
        "MOTIVO_STATUS": list(reason_status.values())[0],
        "RESUMO": summary,
        "QTD_TENTATIVAS": 1,
        "NOME_MAILING": raw_mailing["MAILING"],
        "SEGMENTACAO1": "CONTROLE_POS",
    }
