"""
KMET - KiessMetrics Agent
Handles analytics, reporting, and performance tracking.
"""

from __future__ import annotations
import logging
from datetime import datetime
from pathlib import Path
from typing import Optional

from ..core.agent import BaseAgent
from ..core.memory import MemoryEngine
from ..skills.analytics import AnalyticsSkill

logger = logging.getLogger(__name__)


class KiessMetricsAgent(BaseAgent):
    """
    Metrics agent responsible for:
    - Calculating sequence performance
    - Tracking deliverability
    - Generating reports
    - A/B test analysis
    """

    codename = "KMET"
    name = "KiessMetrics"
    description = "Analytics, deliverability, reporting"

    def __init__(self, config: dict, memory: MemoryEngine):
        super().__init__(config, memory)
        self.analytics_skill = AnalyticsSkill(config)

    def run(self, task: str, **kwargs) -> str:
        """
        Execute an analytics task.

        Supported tasks:
        - report: Generate weekly report
        - funnel: Show sequence funnel
        - deliverability: Show deliverability stats
        - pipeline: Show prospect pipeline
        - analyze: Analyze performance with LLM insights
        """
        self.update_status("running", task)

        try:
            if task == "report" or "report" in task.lower():
                return self._handle_report(**kwargs)
            elif task == "funnel" or "funnel" in task.lower():
                return self._handle_funnel(**kwargs)
            elif task == "deliverability" or "deliver" in task.lower():
                return self._handle_deliverability(**kwargs)
            elif task == "pipeline" or "pipeline" in task.lower():
                return self._handle_pipeline(**kwargs)
            elif task == "analyze" or "analy" in task.lower():
                return self._handle_analyze(**kwargs)
            else:
                return self._handle_natural_language(task, **kwargs)

        except Exception as e:
            logger.error(f"[KMET] Error: {e}")
            self.update_status("error", task)
            return f"Error: {str(e)}"

        finally:
            self.update_status("idle")

    def _handle_report(self, save: bool = True, **kwargs) -> str:
        """Generate weekly report."""
        # Load all data
        sequences = self.memory.load_data("sequences")
        contacts = self.memory.load_data("contacts")
        enrollments = self.memory.load_data("enrollments")
        messages = self.memory.load_data("messages")
        replies = self.memory.load_data("replies")

        # Generate report
        report = self.analytics_skill.generate_weekly_report(
            sequences, contacts, enrollments, messages, replies
        )

        # Save report
        if save:
            reports_dir = Path(self.config.get("workspace", {}).get("reports_dir", "./workspace/reports"))
            reports_dir.mkdir(parents=True, exist_ok=True)

            filename = f"weekly_report_{datetime.now().strftime('%Y%m%d')}.md"
            report_path = reports_dir / filename
            report_path.write_text(report, encoding="utf-8")

            self.memory.log("kmet", f"**Generated Weekly Report**\nSaved to: {report_path}")

        return report

    def _handle_funnel(self, sequence_id: str = None, **kwargs) -> str:
        """Show sequence funnel metrics."""
        sequences = self.memory.load_data("sequences")
        enrollments = self.memory.load_data("enrollments")
        messages = self.memory.load_data("messages")
        replies = self.memory.load_data("replies")

        if sequence_id:
            # Single sequence
            sequence = None
            for s in sequences:
                if s["id"] == sequence_id:
                    sequence = s
                    break

            if not sequence:
                return f"Sequence {sequence_id} not found"

            funnel = self.analytics_skill.calculate_sequence_funnel(
                sequence_id, enrollments, messages, replies
            )

            output = f"**Funnel: {sequence['name']}**\n\n"
            output += "```\n"
            output += f"Enrolled:        {funnel['enrolled']:>5}\n"
            output += f"  └─ Active:     {funnel['active']:>5}\n"
            output += f"  └─ Completed:  {funnel['completed']:>5}\n"
            output += f"Sent:            {funnel['sent']:>5}\n"
            output += f"  └─ Delivered:  {funnel['delivered']:>5} ({funnel['rates']['delivery_rate']:.1%})\n"
            output += f"  └─ Bounced:    {funnel['bounced']:>5}\n"
            output += f"Opened:          {funnel['opened']:>5} ({funnel['rates']['open_rate']:.1%})\n"
            output += f"Replied:         {funnel['replied']:>5} ({funnel['rates']['reply_rate']:.1%})\n"
            output += f"  └─ Positive:   {funnel['positive_replies']:>5}\n"
            output += f"  └─ Meetings:   {funnel['meetings']:>5}\n"
            output += "```"

            return output

        else:
            # All sequences
            output = "**Sequence Funnels**\n\n"
            output += "| Sequence | Enrolled | Sent | Replied | Rate |\n"
            output += "|----------|----------|------|---------|------|\n"

            for seq in sequences:
                funnel = self.analytics_skill.calculate_sequence_funnel(
                    seq["id"], enrollments, messages, replies
                )
                output += f"| {seq['name'][:20]} | {funnel['enrolled']} | {funnel['sent']} | {funnel['replied']} | {funnel['rates']['reply_rate']:.1%} |\n"

            return output

    def _handle_deliverability(self, days: int = 30, **kwargs) -> str:
        """Show deliverability stats."""
        messages = self.memory.load_data("messages")

        stats = self.analytics_skill.calculate_deliverability(messages, days)

        output = f"**Deliverability (Last {days} Days)**\n\n"
        output += f"- Total Sent: {stats['total_sent']}\n"
        output += f"- Delivered: {stats['delivered']} ({stats['delivery_rate']:.1%})\n"
        output += f"- Bounced: {stats['bounced']} ({stats['bounce_rate']:.1%})\n"
        output += f"  - Hard: {stats['hard_bounces']}\n"
        output += f"  - Soft: {stats['soft_bounces']}\n"

        # Health assessment
        if stats['bounce_rate'] > 0.05:
            output += "\n⚠️ **Warning**: Bounce rate is above 5%. Consider cleaning your list."
        elif stats['bounce_rate'] > 0.02:
            output += "\n⚡ **Notice**: Bounce rate is elevated. Monitor closely."
        else:
            output += "\n✅ Deliverability is healthy."

        return output

    def _handle_pipeline(self, **kwargs) -> str:
        """Show prospect pipeline."""
        contacts = self.memory.load_data("contacts")

        pipeline = self.analytics_skill.calculate_pipeline(contacts)

        output = "**Prospect Pipeline**\n\n"
        output += f"Total Contacts: {pipeline['total_contacts']}\n\n"

        output += "**Status**\n"
        for status, count in sorted(pipeline['status_distribution'].items(), key=lambda x: -x[1]):
            bar_len = int(count / pipeline['total_contacts'] * 20) if pipeline['total_contacts'] > 0 else 0
            bar = "█" * bar_len + "░" * (20 - bar_len)
            output += f"  {status:12} {bar} {count}\n"

        output += "\n**ICP Score**\n"
        for bucket, count in pipeline['icp_distribution'].items():
            bar_len = int(count / pipeline['total_contacts'] * 20) if pipeline['total_contacts'] > 0 else 0
            bar = "█" * bar_len + "░" * (20 - bar_len)
            output += f"  {bucket:12} {bar} {count}\n"

        output += f"\n**Key Metrics**\n"
        output += f"- Qualified: {pipeline['qualified_count']}\n"
        output += f"- DNC: {pipeline['dnc_count']}\n"
        output += f"- Bounced: {pipeline['bounced_count']}\n"
        output += f"- Conversion Rate: {pipeline['conversion_rate']:.1%}\n"

        return output

    def _handle_analyze(self, **kwargs) -> str:
        """Analyze performance with LLM insights."""
        # Gather all metrics
        sequences = self.memory.load_data("sequences")
        contacts = self.memory.load_data("contacts")
        enrollments = self.memory.load_data("enrollments")
        messages = self.memory.load_data("messages")
        replies = self.memory.load_data("replies")

        deliverability = self.analytics_skill.calculate_deliverability(messages, days=30)
        reply_analysis = self.analytics_skill.analyze_replies(replies, days=30)
        pipeline = self.analytics_skill.calculate_pipeline(contacts)

        # Build context
        context = f"""Performance Data (Last 30 Days):

DELIVERABILITY:
- Sent: {deliverability['total_sent']}
- Delivery Rate: {deliverability['delivery_rate']:.1%}
- Bounce Rate: {deliverability['bounce_rate']:.1%}

REPLIES:
- Total: {reply_analysis['total_replies']}
- Positive Rate: {reply_analysis['positive_rate']:.1%}
- Intent Distribution: {reply_analysis['intent_distribution']}
- Objection Distribution: {reply_analysis['objection_distribution']}

PIPELINE:
- Total Contacts: {pipeline['total_contacts']}
- Qualified: {pipeline['qualified_count']}
- Conversion Rate: {pipeline['conversion_rate']:.1%}
- Status: {pipeline['status_distribution']}

SEQUENCES:
- Active: {sum(1 for s in sequences if s.get('status') == 'active')}
- Total enrolled: {len(enrollments)}
"""

        # Get LLM analysis
        response = self.think(
            user_message="Analyze this sales outreach performance data and provide 3-5 actionable insights to improve results. Focus on specific opportunities and problems.",
            context=context,
        )

        output = "**Performance Analysis**\n\n"
        output += response.content

        return output

    def _handle_natural_language(self, task: str, **kwargs) -> str:
        """Handle natural language requests."""
        # Gather summary data
        sequences = self.memory.load_data("sequences")
        contacts = self.memory.load_data("contacts")
        messages = self.memory.load_data("messages")
        replies = self.memory.load_data("replies")

        context = (
            f"Data available:\n"
            f"- {len(sequences)} sequences\n"
            f"- {len(contacts)} contacts\n"
            f"- {len(messages)} messages sent\n"
            f"- {len(replies)} replies received\n"
        )

        response = self.think(
            user_message=task,
            context=context,
        )

        return response.content
