"""Retrieval profiles and operations summary."""
from __future__ import annotations

import csv
import json
from io import StringIO
from typing import TYPE_CHECKING, Any

from .converters import row_to_profile, source_score_to_dict
from .models import RetrievalProfile

if TYPE_CHECKING:
    from .engine import RetrievalLearningEngine


class ProfilesMixin:
    """Mixin for profiles and ops summary functionality."""

    @staticmethod
    def ops_summary(
        engine: "RetrievalLearningEngine",
        *,
        workspace_id: str | None = None,
    ) -> dict[str, Any]:
        """Get operations summary."""
        from .reindex_manager import ReindexManagerMixin
        from .source_documents import SourceDocumentsMixin
        
        requests = ReindexManagerMixin.list_reindex_requests(engine, workspace_id=workspace_id)
        triggers = ReindexManagerMixin.list_reindex_triggers(engine, workspace_id=workspace_id)
        source_documents = SourceDocumentsMixin.list_source_documents(engine, workspace_id=workspace_id)
        
        coalesced_total = 0
        coalesced_request_count = 0
        for item in requests:
            count = int(item.metadata.get("coalesced_count", 0) or 0)
            if count > 0:
                coalesced_request_count += 1
                coalesced_total += count
        
        by_request_status: dict[str, int] = {}
        for status in ("queued", "running", "completed", "failed", "canceled"):
            by_request_status[status] = sum(1 for item in requests if item.status == status)
        
        by_trigger_status: dict[str, int] = {}
        for status in ("open", "acknowledged", "resolved", "closed"):
            by_trigger_status[status] = sum(1 for item in triggers if item.status == status)
        
        latest_request = requests[0].updated_at if requests else None
        latest_trigger = triggers[0].updated_at if triggers else None
        
        return {
            "workspace_id": workspace_id,
            "requests": {
                "total": len(requests),
                "by_status": by_request_status,
                "open_backlog": by_request_status["queued"] + by_request_status["running"] + by_request_status["failed"],
                "latest_updated_at": latest_request,
            },
            "triggers": {
                "total": len(triggers),
                "by_status": by_trigger_status,
                "open_backlog": by_trigger_status["open"] + by_trigger_status["acknowledged"],
                "latest_updated_at": latest_trigger,
            },
            "source_documents": {
                "total": len(source_documents),
                "distinct_sources": len({item.source_key for item in source_documents}),
                "ttl_days": engine.source_document_ttl_days,
                "max_per_source": engine.max_source_documents_per_source,
            },
            "policy": {
                "dedupe_window_seconds": engine.dedupe_window_seconds,
                "source_document_ttl_days": engine.source_document_ttl_days,
                "max_source_documents_per_source": engine.max_source_documents_per_source,
            },
            "coalescing": {
                "coalesced_total": coalesced_total,
                "coalesced_request_count": coalesced_request_count,
            },
        }

    @staticmethod
    def export_source_scores_report(
        engine: "RetrievalLearningEngine",
        *,
        workspace_id: str | None = None,
        format: str = "json",
    ) -> str:
        """Export source scores report."""
        from .retrieval_events import RetrievalEventsMixin
        
        items = [source_score_to_dict(item) for item in RetrievalEventsMixin.list_source_scores(engine, workspace_id=workspace_id)]
        payload = {"workspace_id": workspace_id, "items": items}
        
        if format == "json":
            return json.dumps(payload, indent=2, ensure_ascii=False)
        if format == "csv":
            buffer = StringIO()
            writer = csv.DictWriter(
                buffer,
                fieldnames=[
                    "workspace_id",
                    "source_key",
                    "connector",
                    "usefulness_score",
                    "helpful_count",
                    "harmful_count",
                    "accepted_count",
                    "rejected_count",
                    "last_updated",
                ],
            )
            writer.writeheader()
            for item in items:
                writer.writerow(item)
            return buffer.getvalue()
        raise ValueError(f"Unsupported export format: {format}")

    @staticmethod
    def list_profiles(
        engine: "RetrievalLearningEngine",
        *,
        workspace_id: str | None = None,
        task_type: str | None = None,
        user_segment: str | None = None,
    ) -> list[RetrievalProfile]:
        """List retrieval profiles."""
        clauses = ["workspace_id = ?"]
        params: list[Any] = [engine._workspace_value(workspace_id)]
        if task_type is not None:
            clauses.append("task_type = ?")
            params.append(engine._segment_value(task_type))
        if user_segment is not None:
            clauses.append("user_segment = ?")
            params.append(engine._segment_value(user_segment))
        
        with engine._connect() as connection:
            engine._ensure_schema(connection)
            rows = connection.execute(
                f"""
                SELECT * FROM {engine._table('profiles')}
                WHERE {' AND '.join(clauses)}
                ORDER BY (success_count - failure_count) DESC, success_count DESC, last_updated DESC
                """,
                params,
            ).fetchall()
        return [row_to_profile(row) for row in rows]
