"""Aggregate marketing context for agent."""

from __future__ import annotations

import sqlite3
from typing import Any, Dict, List, Optional

from store_marketing_lib.campaign import _catalog_services, _playbook_path
from store_marketing_lib.segments import run_segment


def build_campaign_context(
    conn: sqlite3.Connection,
    *,
    preset: str,
    segment: Optional[str],
    service: Optional[str],
) -> Dict[str, Any]:
    seg_result = run_segment(conn, preset)
    catalog = _catalog_services(conn, limit=10)
    body: Dict[str, Any] = {
        "preset": seg_result["preset"],
        "total_members": seg_result["total"],
        "segments": seg_result["segments"],
        "catalog_services": catalog,
        "playbook_path": _playbook_path(),
        "agent_instructions": "先读 playbooks/style-profile-workflow.md，再按意图选择 content-generation 或 campaign-planning",
    }
    if segment:
        raw = seg_result["raw_segments"].get(segment) or []
        body["focus_segment"] = segment
        body["focus_count"] = len(raw)
        body["focus_members"] = raw[:20]
    if service:
        row = conn.execute(
            "SELECT name, price FROM catalog_services WHERE name=? AND status='active'",
            (service,),
        ).fetchone()
        if row:
            body["focus_service"] = {"name": row["name"], "price": float(row["price"])}
    return body
