"""Context assembly for external-admin assistant jobs."""
from __future__ import annotations

from typing import Any
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.external_admin.repository import (
    AssistantProjectSettingsRepository,
    ExternalAdminChatMessageRepository,
    ExternalAdminChatSessionRepository,
    ExternalAdminInstallationRepository,
    SiteUnderstandingRunRepository,
)
from src.integrations.cloud_control_client import get_cloud_client_for_workspace


async def build_wordpress_chat_context(
    db: AsyncSession,
    *,
    installation_id: UUID,
    session_id: UUID,
    history_limit: int = 20,
) -> dict[str, Any]:
    """Build compact context for a Core-owned WordPress assistant job.

    The returned object is intentionally structured and conservative. Large site
    objects should live in Cloud D1/R2 and be referenced here as summaries,
    hashes, and rollback pointers.
    """
    installation = await ExternalAdminInstallationRepository(db).get_by_id(installation_id)
    session = await ExternalAdminChatSessionRepository(db).get(session_id)
    if not installation or not session:
        return {"ok": False, "error": "installation_or_session_not_found"}

    settings = await AssistantProjectSettingsRepository(db).get(installation.project_id)
    latest_understanding = await SiteUnderstandingRunRepository(db).get_latest_completed_for_installation(
        installation.id
    )
    messages = await ExternalAdminChatMessageRepository(db).list_recent_by_session(
        session.id,
        limit=history_limit,
    )

    cloud_client = await get_cloud_client_for_workspace(installation.workspace_id, db)
    site_shape = await cloud_client.get_wp_site_shape_summary(
        project_id=str(installation.project_id),
        installation_id=str(installation.id),
    )

    return {
        "ok": True,
        "platform": installation.installation_type,
        "installation": {
            "id": str(installation.id),
            "project_id": str(installation.project_id),
            "workspace_id": str(installation.workspace_id),
            "site_url": installation.site_url,
            "shop_domain": installation.shop_domain,
            "status": installation.status,
            "plugin_file_hash": installation.plugin_file_hash,
            "companion_version": installation.companion_version,
            "companion_file_hash": installation.companion_file_hash,
            "last_heartbeat_at": installation.last_heartbeat_at.isoformat()
            if installation.last_heartbeat_at
            else None,
        },
        "assistant_settings": {
            "ai_usage_mode": settings.ai_usage_mode if settings else "p2hs_credits",
            "action_approval_required": settings.action_approval_required if settings else True,
            "allowed_capabilities": settings.allowed_capabilities if settings else [],
        },
        "site_understanding": {
            "status": latest_understanding.status if latest_understanding else "missing",
            "run_id": str(latest_understanding.id) if latest_understanding else None,
            "completed_at": latest_understanding.completed_at.isoformat()
            if latest_understanding and latest_understanding.completed_at
            else None,
            "summary": latest_understanding.summary_json if latest_understanding else None,
        },
        "cloud_site_shape": site_shape,
        "conversation_history": [
            {
                "id": str(message.id),
                "role": message.role,
                "content": message.content,
                "created_at": message.created_at.isoformat(),
            }
            for message in messages
        ],
    }


async def build_external_admin_chat_context(
    db: AsyncSession,
    *,
    installation_id: UUID,
    session_id: UUID,
    history_limit: int = 20,
) -> dict[str, Any]:
    """Build compact context for WordPress or Shopify assistant jobs."""
    return await build_wordpress_chat_context(
        db,
        installation_id=installation_id,
        session_id=session_id,
        history_limit=history_limit,
    )
