"""Marketing intelligence engine that ranks and scores enumerated campaigns.""" from __future__ import annotations import base64 import importlib import json import os import re from dataclasses import dataclass from functools import lru_cache from statistics import mean from typing import Any, Dict, List, Sequence, Tuple try: # pragma: no cover - optional dependency that may not be installed in tests from google.ads.googleads.client import GoogleAdsClient # type: ignore except ImportError: # pragma: no cover - gracefully handled when SDK missing GoogleAdsClient = None # type: ignore try: # pragma: no cover - optional dependency that may not be installed in tests from google.oauth2 import service_account # type: ignore except ImportError: # pragma: no cover - gracefully handled when SDK missing service_account = None # type: ignore try: # pragma: no cover - optional dependency that may not be installed in tests import stripe # type: ignore except ImportError: # pragma: no cover - gracefully handled when SDK missing stripe = None # type: ignore try: # pragma: no cover - optional dependency that may not be installed in tests from paypalcheckoutsdk.core import ( # type: ignore PayPalHttpClient, LiveEnvironment, SandboxEnvironment, ) except ImportError: # pragma: no cover - gracefully handled when SDK missing PayPalHttpClient = None # type: ignore LiveEnvironment = None # type: ignore SandboxEnvironment = None # type: ignore try: # pragma: no cover - optional dependency for AWS integrations import boto3 # type: ignore except ImportError: # pragma: no cover - gracefully handled when SDK missing boto3 = None # type: ignore MARKETING_ENUMERATION = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "enumerations", "marketing_500.txt" ) MARKETING_BENCHMARKS = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "marketing_benchmarks.json" ) CJ_OFFERS_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "cj_offers.json" ) AMAZON_MARKETPLACE_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "amazon_marketplace.json" ) EBAY_MARKETPLACE_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "ebay_marketplace.json" ) AWS_GROWTH_PLAYBOOKS = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "aws_growth_playbooks.json" ) CHANNEL_INVESTMENTS_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "channel_investments.json", ) AUTOMATION_SPRINTS_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "automation_sprints.json", ) PERFORMANCE_MEMORY_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "performance_memory.json", ) COMPETITIVE_LANDSCAPE_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "competitive_landscape.json", ) INFLUENCER_PARTNERS_DATASET = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "influencer_partners.json", ) AWS_GROWTH_PLAYBOOKS = os.path.join( os.path.dirname(__file__), "..", "..", "daemon", "datasets", "aws_growth_playbooks.json" ) requests_spec = importlib.util.find_spec("requests") requests = importlib.import_module("requests") if requests_spec else None def _load_lines(path: str) -> List[str]: with open(path, "r", encoding="utf-8") as handle: return [line.strip() for line in handle if line.strip()] @dataclass(slots=True) class MarketingCampaign: """Structured representation for one marketing campaign idea.""" raw: str channel: str audience: str offer: str objective: str @classmethod def parse(cls, raw: str) -> "MarketingCampaign": text = raw.strip().rstrip(".") if not text.lower().startswith("campaign:"): raise ValueError(f"Unsupported campaign format: {raw}") body = text[len("Campaign:") :].strip() try: channel, remainder = body.split("targeting", 1) audience, remainder = remainder.split("leveraging", 1) offer, objective = remainder.split(" to ", 1) except ValueError as exc: # pragma: no cover - enumeration should be well formed raise ValueError(f"Malformed campaign sentence: {raw}") from exc return cls( raw=raw, channel=channel.strip(), audience=audience.strip(), offer=offer.strip(), objective=objective.strip().rstrip("."), ) @dataclass(slots=True) class CampaignMetrics: """Statistical expectations for a marketing campaign.""" expected_roi: float expected_ctr: float confidence: float drivers: Dict[str, float] @dataclass(slots=True) class BudgetProfile: """Baseline investment expectations for a marketing channel.""" channel: str keywords: List[str] baseline_cpc: float baseline_cpl: float avg_conversion_rate: float avg_roi: float recommended_monthly_spend: float @dataclass(slots=True) class BudgetAllocation: """Recommended allocation for a marketing campaign channel.""" channel: str audience_focus: str offer: str objective: str allocation_usd: float allocation_weight: float expected_leads: float expected_revenue: float rationale: str source: str notes: str | None = None @dataclass(slots=True) class BudgetPlan: """Portfolio-level budget recommendation summary.""" total_budget: float allocations: List[BudgetAllocation] expected_revenue: float expected_roi: float payback_period_weeks: float summary: str @dataclass(slots=True) class AutomationTask: """Time-boxed task within an automation sprint.""" start_minute: int end_minute: int activity: str outcome: str tooling: List[str] kpis: List[str] automation_level: str source: str @dataclass(slots=True) class AutomationSprint: """Three-hour automation run composed of sequential tasks.""" total_minutes: int stage: str focus: str summary: str tasks: List[AutomationTask] notes: str | None = None source: str = "automation_playbooks" @dataclass(slots=True) class PerformanceMemoryEntry: """Historical marketing learning captured from closed-loop experiments.""" play_name: str stage: str audience_focus: str channel: str tags: List[str] summary: str wins: List[str] losses: List[str] next_actions: List[str] kpi_focus: List[str] confidence: float source: str = "performance_memory" notes: str | None = None @dataclass(slots=True) class LearningLoopRecommendation: """Actionable recommendation generated from the learning memory.""" play_name: str stage: str audience_focus: str channel: str learning: str wins: List[str] losses: List[str] next_actions: List[str] kpi_focus: List[str] confidence: float source: str notes: str | None = None @dataclass(slots=True) class ExcellenceSummary: """Composite readiness score describing how robust the ANI recommendations are.""" excellence_index: float maturity_level: str headline: str strengths: List[str] watchouts: List[str] process_coverage: Dict[str, float] notes: str | None = None @dataclass(slots=True) class StrategicDirective: """Directive that fuses multiple process signals into a prioritized motion.""" name: str priority: int objective: str primary_channel: str supporting_channels: List[str] investment_usd: float | None expected_revenue_usd: float | None confidence: float time_horizon_hours: int north_star_metric: str supporting_metrics: List[str] action_steps: List[str] dependencies: List[str] risk_mitigations: List[str] inspiration: str source: str = "ani_orchestration" notes: str | None = None @dataclass(slots=True) class ExecutivePlaybook: """Cross-process action plan that guides autonomous execution.""" headline: str focus: str urgency: str north_star_metric: str total_budget_usd: float | None expected_revenue_usd: float | None confidence: float directives: List[StrategicDirective] summary: str notes: str | None = None @dataclass(slots=True) class ScenarioProjection: """Scenario-level forecast for autonomous marketing execution.""" scenario: str expected_revenue: float expected_roi: float probability: float confidence: float accelerators: List[str] stabilizers: List[str] watchouts: List[str] source: str = "scenario_planner" notes: str | None = None @dataclass(slots=True) class ScenarioAnalysis: """Aggregated scenario planning summary.""" headline: str summary: str projections: List[ScenarioProjection] confidence: float accelerators: List[str] stabilizers: List[str] source: str = "scenario_planner" notes: str | None = None class ScenarioPlanningProcess: """Synthesizes optimistic, base, and conservative revenue scenarios.""" def __init__(self, volatility_floor: float = 0.15) -> None: self._volatility_floor = volatility_floor def _estimate_budget( self, diagnostics: PromptDiagnostics, campaigns: Sequence[CampaignScore] ) -> float: stage_baseline = { "awareness": 18000.0, "consideration": 22000.0, "conversion": 28000.0, "retention": 20000.0, } base = stage_baseline.get(diagnostics.stage, 22000.0) focus = diagnostics.focus.lower() if "enterprise" in focus: base *= 1.45 elif "startup" in focus: base *= 0.9 elif "consumer" in focus: base *= 0.8 if diagnostics.urgency == "urgent": base *= 1.25 elif diagnostics.urgency == "time-sensitive": base *= 1.1 avg_roi = mean(score.metrics.expected_roi for score in campaigns) base *= max(0.8, min(1.6, avg_roi / 2.0)) return round(max(7500.0, base), 2) @staticmethod def _signal_accelerators( google_ads: Sequence[GoogleCampaignPerformance] | None, cj_affiliate: Sequence[CJAffiliateRecommendation] | None, amazon: Sequence[AmazonProductRecommendation] | None, ebay: Sequence[EbayRevenuePlay] | None, aws: Sequence[AWSRevenueRecommendation] | None, stripe: Sequence[StripeMonetizationPlan] | None, paypal: Sequence[PayPalMonetizationPlan] | None, influencers: Sequence[InfluencerRecommendation] | None, ) -> List[str]: accelerators: List[str] = [] if google_ads: roas = mean(perf.roas for perf in google_ads) if roas >= 3.5: accelerators.append(f"Google Ads ROAS averaging {roas:.2f}x supports paid scale") if cj_affiliate: revenue = mean(rec.projected_monthly_revenue for rec in cj_affiliate) if revenue > 15000: accelerators.append( f"CJ affiliate programs forecast ${revenue:,.0f} monthly expansion" ) if amazon: conversion = mean(rec.rating for rec in amazon) if conversion >= 4.2: accelerators.append("Amazon marketplace sentiment reinforces conversion confidence") if ebay: margin = mean(play.projected_profit_margin for play in ebay) velocity = mean(play.sold_per_month for play in ebay) if margin >= 0.25 and velocity >= 100: accelerators.append( "eBay partner inventory blends high-margin payouts with rapid sell-through" ) if aws: roi = mean(rec.projected_roi for rec in aws) if roi >= 2.5: accelerators.append("AWS growth plays carry multi-service ROI leverage") if stripe: price = mean(plan.price_usd for plan in stripe) if price >= 99: accelerators.append("Stripe monetization supports premium pricing uplift") if paypal: payout_focus = {plan.payout_schedule for plan in paypal} if "daily" in payout_focus: accelerators.append("PayPal payouts unlocked daily revenue capture velocity") elif paypal: accelerators.append("PayPal commerce streamlines cashflow-ready offers") if influencers: avg_roi = mean(rec.projected_roi for rec in influencers) avg_reach = mean(rec.estimated_reach for rec in influencers) if avg_roi >= 4.0: accelerators.append( f"Influencer partnerships forecast {avg_roi:.1f}x ROI with amplified reach" ) elif avg_reach >= 5000: accelerators.append( f"Influencer partners extend campaigns to {avg_reach:,.0f}+ engaged prospects" ) return accelerators @staticmethod def _stabilizers(diagnostics: PromptDiagnostics, budget: BudgetPlan | None) -> List[str]: stabilizers: List[str] = [] if diagnostics.recommended_kpis: stabilizers.append(f"Instrument KPI guardrails around {diagnostics.recommended_kpis[0]}") if budget and budget.allocations: top_channel = budget.allocations[0].channel stabilizers.append(f"Phase spend across {top_channel} with weekly optimization cycles") return stabilizers def analyze( self, prompt: str, diagnostics: PromptDiagnostics, campaigns: Sequence[CampaignScore], *, budget: BudgetPlan | None, google_ads: Sequence[GoogleCampaignPerformance] | None, cj_affiliate: Sequence[CJAffiliateRecommendation] | None, amazon: Sequence[AmazonProductRecommendation] | None, ebay: Sequence[EbayRevenuePlay] | None, aws: Sequence[AWSRevenueRecommendation] | None, stripe: Sequence[StripeMonetizationPlan] | None, paypal: Sequence[PayPalMonetizationPlan] | None, crypto: Sequence[CryptoMarketSnapshot] | None, influencers: Sequence[InfluencerRecommendation] | None, limit: int = 3, ) -> ScenarioAnalysis: if not campaigns: raise ValueError("Scenario planning requires campaign scores") top = list(campaigns[: max(1, limit)]) avg_roi = mean(score.metrics.expected_roi for score in top) avg_confidence = mean(score.metrics.confidence for score in top) avg_ctr = mean(score.metrics.expected_ctr for score in top) base_budget = ( budget.total_budget if budget and budget.total_budget > 0 else self._estimate_budget(diagnostics, top) ) base_revenue = ( budget.expected_revenue if budget and budget.expected_revenue > 0 else round(base_budget * max(1.1, avg_roi), 2) ) base_roi = round(base_revenue / base_budget, 2) if base_budget else round(avg_roi, 2) volatility = self._volatility_floor if diagnostics.urgency == "urgent": volatility += 0.1 elif diagnostics.urgency == "time-sensitive": volatility += 0.05 if diagnostics.risk_signals: volatility += 0.08 if crypto and any(snapshot.change_24h and abs(snapshot.change_24h) > 5 for snapshot in crypto): volatility += 0.05 volatility = min(0.5, max(self._volatility_floor, volatility)) optimistic_multiplier = 1 + volatility conservative_multiplier = max(0.45, 1 - volatility) optimistic_revenue = round(base_revenue * optimistic_multiplier, 2) conservative_revenue = round(base_revenue * conservative_multiplier, 2) optimistic_roi = round(base_roi * (1 + volatility / 1.5), 2) conservative_roi = round(base_roi * (1 - volatility / 1.2), 2) optimistic_conf = min(0.99, avg_confidence + (0.12 - volatility / 2)) base_conf = min(0.95, max(0.25, avg_confidence)) conservative_conf = max(0.2, avg_confidence - volatility / 2) optimistic_prob = max(0.18, 0.32 - (volatility - self._volatility_floor) * 0.6) conservative_prob = max(0.22, 0.28 + (volatility - self._volatility_floor) * 0.5) base_prob = max(0.3, 1.0 - optimistic_prob - conservative_prob) total = optimistic_prob + base_prob + conservative_prob optimistic_prob = round(optimistic_prob / total, 2) base_prob = round(base_prob / total, 2) conservative_prob = round(conservative_prob / total, 2) accelerators = self._signal_accelerators( google_ads, cj_affiliate, amazon, ebay, aws, stripe, paypal, influencers ) stabilizers = self._stabilizers(diagnostics, budget) if avg_ctr > 0.6: accelerators.append("Benchmark CTR momentum indicates creative resonance") if len(accelerators) < 2: accelerators.append("Cross-process enrichment unlocks multi-channel leverage") if not stabilizers: stabilizers.append("Institute weekly analytics reviews to course-correct") risk_watchouts = diagnostics.risk_signals[:2] if not risk_watchouts: risk_watchouts = ["Monitor acquisition efficiency as spend scales"] projections = [ ScenarioProjection( scenario="optimistic", expected_revenue=optimistic_revenue, expected_roi=optimistic_roi, probability=optimistic_prob, confidence=round(optimistic_conf, 2), accelerators=accelerators, stabilizers=stabilizers, watchouts=["Ensure fulfillment capacity scales with demand"], ), ScenarioProjection( scenario="base", expected_revenue=round(base_revenue, 2), expected_roi=round(base_roi, 2), probability=base_prob, confidence=round(base_conf, 2), accelerators=accelerators, stabilizers=stabilizers, watchouts=risk_watchouts, ), ScenarioProjection( scenario="conservative", expected_revenue=conservative_revenue, expected_roi=round(conservative_roi, 2), probability=round(conservative_prob, 2), confidence=round(conservative_conf, 2), accelerators=accelerators, stabilizers=stabilizers, watchouts=["Reserve contingency budget to reallocate into proven channels"], ), ] primary_channels = {score.campaign.channel for score in top[:2]} summary = ( f"Model optimistic, base, and conservative revenue trajectories for {diagnostics.stage} " f"outcomes targeting {diagnostics.focus}." ) headline = ( f"Scenario coverage for {', '.join(sorted(primary_channels))} anchored in {diagnostics.focus}." ) notes = ( f"Volatility factor {volatility:.2f} derives from urgency={diagnostics.urgency} and risk signals" ) return ScenarioAnalysis( headline=headline, summary=summary, projections=projections, confidence=round(base_conf, 2), accelerators=accelerators, stabilizers=stabilizers, notes=notes, ) class PerformanceMemory: """Loads and scores historical marketing learnings.""" def __init__(self, entries: Sequence[PerformanceMemoryEntry]): if not entries: raise ValueError("PerformanceMemory requires at least one entry") self._entries = list(entries) @classmethod def from_file(cls, path: str = PERFORMANCE_MEMORY_DATASET) -> "PerformanceMemory": with open(path, "r", encoding="utf-8") as handle: payload = json.load(handle) entries = [] for record in payload: entries.append( PerformanceMemoryEntry( play_name=record["play_name"], stage=record["stage"], audience_focus=record["audience_focus"], channel=record["channel"], tags=[tag.lower() for tag in record.get("tags", [])], summary=record["summary"], wins=record.get("wins", []), losses=record.get("losses", []), next_actions=record.get("next_actions", []), kpi_focus=[str(kpi) for kpi in record.get("kpi_focus", [])], confidence=float(record.get("confidence", 0.5)), source=record.get("source", "performance_memory"), notes=record.get("notes"), ) ) return cls(entries) @property def entries(self) -> List[PerformanceMemoryEntry]: return list(self._entries) @dataclass(slots=True) class CompetitiveLandscapeEntry: """Competitive signal captured from market monitoring.""" competitor: str channel: str summary: str strengths: List[str] weaknesses: List[str] recommended_play: str share_of_voice: float signal_intensity: float keywords: List[str] maturity: str source: str notes: str | None = None @dataclass(slots=True) class CompetitiveSignal: """Recommendation derived from the competitive landscape dataset.""" competitor: str channel: str summary: str strengths: List[str] weaknesses: List[str] recommended_play: str share_of_voice: float signal_intensity: float threat_level: str focus_alignment: float source: str notes: str | None = None class CompetitiveLandscape: """Loads competitive marketing signals from curated monitoring.""" def __init__(self, entries: Sequence[CompetitiveLandscapeEntry]): if not entries: raise ValueError("CompetitiveLandscape requires at least one entry") self._entries = list(entries) @classmethod def from_file( cls, path: str = COMPETITIVE_LANDSCAPE_DATASET ) -> "CompetitiveLandscape": with open(path, "r", encoding="utf-8") as handle: payload = json.load(handle) entries: List[CompetitiveLandscapeEntry] = [] for record in payload: entries.append( CompetitiveLandscapeEntry( competitor=record["competitor"], channel=record["channel"], summary=record["summary"], strengths=list(record.get("strengths", [])), weaknesses=list(record.get("weaknesses", [])), recommended_play=record["recommended_play"], share_of_voice=float(record.get("share_of_voice", 0.0)), signal_intensity=float(record.get("signal_intensity", 0.0)), keywords=[str(token).lower() for token in record.get("keywords", [])], maturity=record.get("maturity", "growth"), source=record.get("source", "competitive_monitor"), notes=record.get("notes"), ) ) return cls(entries) @property def entries(self) -> List[CompetitiveLandscapeEntry]: return list(self._entries) class LearningLoopProcess: """Transforms prompt intelligence into closed-loop learning recommendations.""" def __init__(self, memory: PerformanceMemory | None = None): self._memory = memory or PerformanceMemory.from_file() def recommend( self, prompt: str, diagnostics: "PromptDiagnostics", campaigns: Sequence["CampaignScore"], limit: int = 3, ) -> List[LearningLoopRecommendation]: tokens = MarketingIntelligenceEngine._keyword_set(prompt) diag_tokens: set[str] = set() for bucket in (diagnostics.opportunities, diagnostics.recommended_kpis): for item in bucket: diag_tokens.update(MarketingIntelligenceEngine._keyword_set(item)) focus_tokens = set(MarketingIntelligenceEngine._keyword_set(diagnostics.focus)) urgency_bonus = 0.6 if diagnostics.urgency != "standard" else 0.0 channels = {score.campaign.channel.lower() for score in campaigns} audiences = {score.campaign.audience.lower() for score in campaigns} scored: List[Tuple[float, PerformanceMemoryEntry]] = [] for entry in self._memory.entries: entry_tags = set(entry.tags) kpi_tokens: set[str] = set() for kpi in entry.kpi_focus: kpi_tokens.update(MarketingIntelligenceEngine._keyword_set(kpi)) combined_tags = entry_tags.union(kpi_tokens) tag_hits = len(combined_tags.intersection(tokens)) diag_hits = len(combined_tags.intersection(diag_tokens)) focus_hits = len(combined_tags.intersection(focus_tokens)) stage_bonus = 1.8 if entry.stage.lower() == diagnostics.stage.lower() else 0.0 channel_bonus = 1.0 if entry.channel.lower() in channels else 0.0 audience_bonus = 0.0 for audience in audiences: if entry.audience_focus.lower() in audience or any(tag in audience for tag in combined_tags): audience_bonus = 0.9 break focus_bonus = 0.7 if focus_hits else 0.0 opportunity_bonus = 0.5 * diag_hits keyword_bonus = 0.4 * tag_hits score = ( entry.confidence + keyword_bonus + opportunity_bonus + focus_bonus + stage_bonus + channel_bonus + audience_bonus + urgency_bonus ) scored.append((score, entry)) ranked = sorted(scored, key=lambda item: item[0], reverse=True)[: max(1, limit)] recommendations: List[LearningLoopRecommendation] = [] for _, entry in ranked: recommendations.append( LearningLoopRecommendation( play_name=entry.play_name, stage=entry.stage, audience_focus=entry.audience_focus, channel=entry.channel, learning=entry.summary, wins=entry.wins, losses=entry.losses, next_actions=entry.next_actions, kpi_focus=entry.kpi_focus, confidence=round(min(0.99, max(0.0, entry.confidence)), 2), source=entry.source, notes=entry.notes, ) ) return recommendations class CompetitiveIntelligenceProcess: """Turns competitive monitoring into counter-moves for the marketing ANI.""" def __init__(self, landscape: CompetitiveLandscape | None = None): self._landscape = landscape or CompetitiveLandscape.from_file() def signals( self, prompt: str, diagnostics: "PromptDiagnostics", campaigns: Sequence["CampaignScore"], limit: int = 3, ) -> List[CompetitiveSignal]: prompt_tokens = set(MarketingIntelligenceEngine._keyword_set(prompt)) focus_tokens = set(MarketingIntelligenceEngine._keyword_set(diagnostics.focus)) combined_tokens = prompt_tokens.union(focus_tokens) campaign_channels = {score.campaign.channel.lower() for score in campaigns} stage_alignment = { "paid search": "conversion", "paid social": "consideration", "content syndication": "awareness", "outbound sdr": "conversion", "lifecycle automation": "retention", "partner ecosystem": "consideration", } scored: List[Tuple[float, CompetitiveLandscapeEntry, float]] = [] for entry in self._landscape.entries: entry_tokens = set(entry.keywords) keyword_hits = len(entry_tokens.intersection(prompt_tokens)) focus_hits = len(entry_tokens.intersection(focus_tokens)) overlap_hits = len(entry_tokens.intersection(combined_tokens)) share_component = entry.share_of_voice * 1.5 intensity_component = entry.signal_intensity keyword_component = 0.25 * keyword_hits focus_component = 0.35 * focus_hits channel_component = 0.6 if entry.channel.lower() in campaign_channels else 0.0 stage_tag = stage_alignment.get(entry.channel.lower()) stage_component = 0.4 if stage_tag == diagnostics.stage.lower() else 0.0 maturity_component = 0.3 if entry.maturity.lower() in diagnostics.focus.lower() else 0.0 total_score = ( share_component + intensity_component + keyword_component + focus_component + channel_component + stage_component + maturity_component ) focus_alignment = min(1.0, overlap_hits / max(1, len(entry_tokens))) scored.append((total_score, entry, focus_alignment)) ranked = sorted(scored, key=lambda item: item[0], reverse=True)[: max(1, limit)] signals: List[CompetitiveSignal] = [] for total_score, entry, alignment in ranked: threat_index = entry.share_of_voice * 1.5 + entry.signal_intensity if threat_index >= 1.65: threat_level = "high" elif threat_index >= 1.15: threat_level = "medium" else: threat_level = "low" signals.append( CompetitiveSignal( competitor=entry.competitor, channel=entry.channel, summary=entry.summary, strengths=entry.strengths, weaknesses=entry.weaknesses, recommended_play=entry.recommended_play, share_of_voice=round(entry.share_of_voice, 2), signal_intensity=round(entry.signal_intensity, 2), threat_level=threat_level, focus_alignment=round(alignment, 2), source=entry.source, notes=entry.notes, ) ) return signals class MarketingBenchmarks: """Loads benchmark statistics and produces campaign metrics.""" def __init__(self, baseline: Dict[str, float], components: Dict[str, Dict[str, Dict[str, float]]]): self._baseline = baseline self._components = components @classmethod def from_file(cls, path: str = MARKETING_BENCHMARKS) -> "MarketingBenchmarks": with open(path, "r", encoding="utf-8") as handle: payload = json.load(handle) baseline = payload.get("baseline", {"roi": 2.0, "ctr": 0.02, "confidence": 0.6}) components: Dict[str, Dict[str, Dict[str, float]]] = {} for feature, entries in payload.items(): if feature == "baseline": continue components[feature] = {key.lower(): value for key, value in entries.items()} return cls(baseline, components) def _lookup(self, feature: str, value: str) -> Dict[str, float]: cohort = self._components.get(feature, {}) return cohort.get(value.lower(), self._baseline) def metrics_for(self, campaign: MarketingCampaign) -> CampaignMetrics: weights = { "channels": 0.32, "audiences": 0.3, "offers": 0.22, "objectives": 0.16, } baseline_weight = max(0.0, 1.0 - sum(weights.values())) base_roi = self._baseline.get("roi", 2.0) base_ctr = self._baseline.get("ctr", 0.02) base_conf = self._baseline.get("confidence", 0.6) roi = base_roi * baseline_weight ctr = base_ctr * baseline_weight confidence = base_conf * baseline_weight drivers: Dict[str, float] = {} features = { "channels": campaign.channel, "audiences": campaign.audience, "offers": campaign.offer, "objectives": campaign.objective, } for feature, value in features.items(): stats = self._lookup(feature, value) weight = weights[feature] roi += stats.get("roi", base_roi) * weight ctr += stats.get("ctr", base_ctr) * weight confidence += stats.get("confidence", base_conf) * weight drivers[feature.rstrip("s")] = stats.get("roi", base_roi) return CampaignMetrics( expected_roi=roi, expected_ctr=ctr, confidence=min(0.99, max(0.01, confidence)), drivers=drivers, ) @dataclass(slots=True) class CampaignScore: """Composite score for a marketing campaign.""" campaign: MarketingCampaign score: float metrics: CampaignMetrics keyword_coverage: Dict[str, int] @dataclass(slots=True) class PromptDiagnostics: """Structured analysis of a marketing prompt.""" stage: str urgency: str focus: str recommended_kpis: List[str] opportunities: List[str] risk_signals: List[str] keyword_summary: Dict[str, List[str]] confidence: float @dataclass(slots=True) class GrowthExperiment: """Experiment plan produced by the Experiment Growth Grid (EGG) process.""" name: str hypothesis: str primary_metric: str secondary_metrics: List[str] playbook: List[str] confidence: float @dataclass(slots=True) class CJAffiliateOffer: """Offer metadata sourced from the Commission Junction catalog.""" program_name: str advertiser_id: str category: str commission_rate: float epc: float seven_day_epc: float network_rank: int payout_terms: str landing_url: str description: str keywords: List[str] @dataclass(slots=True) class CJAffiliateRecommendation: """Recommendation returned by the CJ affiliate process.""" program_name: str advertiser_id: str category: str commission_rate: float epc: float seven_day_epc: float projected_epc: float projected_monthly_revenue: float network_rank: int payout_terms: str landing_url: str rationale: str source: str notes: str | None = None @dataclass(slots=True) class InfluencerPartner: """Influencer metadata captured from curated partner intelligence.""" name: str platform: str niche: str audience_size: int engagement_rate: float avg_cpm: float collab_formats: List[str] regions: List[str] conversion_focus: str keywords: List[str] case_study: str @dataclass(slots=True) class InfluencerRecommendation: """Recommendation returned by the influencer collaboration process.""" name: str platform: str niche: str collab_format: str audience_size: int engagement_rate: float estimated_reach: int projected_cpm: float projected_leads: int projected_revenue: float projected_roi: float rationale: str source: str notes: str | None = None class InfluencerNetworkCatalog: """Loads curated influencer partner records for offline orchestration.""" def __init__(self, partners: Sequence[InfluencerPartner] | None = None) -> None: if partners is not None: self._partners = list(partners) else: with open(INFLUENCER_PARTNERS_DATASET, "r", encoding="utf-8") as handle: data = json.load(handle) self._partners = [InfluencerPartner(**entry) for entry in data] def match_partners( self, tokens: Sequence[str], focus: str | None, limit: int ) -> List[Tuple[float, InfluencerPartner]]: token_set = {token.lower() for token in tokens} focus_tokens = {token.lower() for token in re.findall(r"[a-zA-Z0-9]+", focus or "")} ranked: List[Tuple[float, InfluencerPartner]] = [] for partner in self._partners: haystack = ( f"{partner.name} {partner.platform} {partner.niche} {partner.conversion_focus} " f"{' '.join(partner.keywords)} {partner.case_study}" ).lower() score = 0.0 keyword_hits = 0 for token in token_set: if token in haystack: score += 1.8 keyword_hits += 1 if token in {keyword.lower() for keyword in partner.keywords}: score += 1.5 keyword_hits += 1 for token in focus_tokens: if token and token in haystack: score += 1.2 if focus and focus.lower() in partner.conversion_focus.lower(): score += 1.0 if focus and focus.lower() in partner.niche.lower(): score += 0.8 score += min(partner.engagement_rate * 20, 2.4) score += min(partner.audience_size / 150000.0, 2.0) score += min(keyword_hits * 0.2, 1.5) if "ai" in token_set and "ai" in {k.lower() for k in partner.keywords}: score += 0.6 ranked.append((score, partner)) ranked.sort(key=lambda item: item[0], reverse=True) return ranked[: max(1, limit)] @dataclass(slots=True) class AmazonMarketplaceListing: """Amazon or AWS Marketplace listing metadata.""" asin: str title: str category: str price_usd: float commission_rate: float rating: float reviews: int url: str keywords: List[str] estimated_monthly_sales: int buy_box_share: float prime_eligible: bool fulfillment_model: str @dataclass(slots=True) class AmazonProductRecommendation: """Recommendation payload produced by the Amazon marketplace process.""" asin: str title: str category: str price_usd: float commission_rate: float rating: float reviews: int estimated_monthly_sales: int buy_box_share: float prime_eligible: bool fulfillment_model: str projected_monthly_revenue: float rationale: str url: str source: str notes: str | None = None class AmazonMarketplaceCatalog: """Loads curated Amazon and AWS marketplace listings for offline use.""" def __init__(self, listings: Sequence[AmazonMarketplaceListing] | None = None): if listings is not None: self._listings = list(listings) else: with open(AMAZON_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle: data = json.load(handle) self._listings = [AmazonMarketplaceListing(**entry) for entry in data] def match_listings( self, tokens: Sequence[str], limit: int, focus: str | None = None ) -> List[Tuple[float, AmazonMarketplaceListing]]: ranked: List[Tuple[float, AmazonMarketplaceListing]] = [] token_set = {token.lower() for token in tokens} for listing in self._listings: haystack = f"{listing.title} {listing.category} {' '.join(listing.keywords)}".lower() score = 0.0 keyword_hits = 0 for token in token_set: if token in haystack: score += 1.5 keyword_hits += 1 if token in {keyword.lower() for keyword in listing.keywords}: score += 1.8 if focus: if focus.lower() in listing.category.lower(): score += 1.2 if focus.lower() in haystack: score += 0.8 score += min(listing.rating / 5.0, 1.0) score += min(listing.reviews / 500.0, 1.0) score += min(listing.estimated_monthly_sales / 400.0, 1.2) score += min(listing.buy_box_share, 1.0) if listing.prime_eligible: score += 0.35 if listing.fulfillment_model.lower().startswith("fba"): score += 0.25 score += keyword_hits * 0.1 ranked.append((score, listing)) ranked.sort(key=lambda item: item[0], reverse=True) return ranked[: max(1, limit)] class AmazonMarketplaceProcess: """Transforms marketplace listings into revenue plans with optional SDK enrichment.""" REQUIRED_ENV_VARS = { "AMAZON_PAAPI_ACCESS_KEY": "access_key", "AMAZON_PAAPI_SECRET_KEY": "[credential removed]", "AMAZON_PAAPI_PARTNER_TAG": "partner_tag", } OPTIONAL_ENV_VARS = { "AWS_REGION": "region", "AWS_PROFILE": "profile", } def __init__( self, catalog: AmazonMarketplaceCatalog | None = None, config: Dict[str, Any] | None = None, ) -> None: self._catalog = catalog or AmazonMarketplaceCatalog() self._config = config or self._config_from_env() self._session = self._build_session() def _build_session(self) -> Any | None: if not self.configured or boto3 is None: return None try: # pragma: no cover - requires boto3 dependency return boto3.session.Session( aws_access_key_id=self._config.get("access_key"), aws_secret_access_key=[credential removed]"secret_key"), region_name=self._config.get("region"), profile_name=self._config.get("profile"), ) except Exception: return None @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in {**cls.REQUIRED_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items(): value = os.getenv(env_var) if value: config[key] = value return config @property def configured(self) -> bool: required = {key for key in self.REQUIRED_ENV_VARS.values()} return required <= self._config.keys() def listings( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[AmazonProductRecommendation]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) focus = None if campaigns: focus = campaigns[0].campaign.channel.split()[0] matches = self._catalog.match_listings(tokens, limit, focus) if not matches: return [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.1 avg_ctr = mean([score.metrics.expected_ctr for score in campaigns]) if campaigns else 0.025 avg_confidence = ( mean([score.metrics.confidence for score in campaigns]) if campaigns else 0.55 ) recommendations: List[AmazonProductRecommendation] = [] for match_score, listing in matches: keyword_overlap = sorted( { token for token in tokens if token in {kw.lower() for kw in listing.keywords} or token in listing.title.lower() } ) intensity = max(0.1, min(2.0, match_score / 4.0)) volume_estimate = listing.estimated_monthly_sales * max(0.4, avg_roi / 2.5) buy_box_lift = 0.75 + listing.buy_box_share * 0.6 prime_lift = 1.18 if listing.prime_eligible else 0.9 confidence_lift = 0.85 + avg_confidence * 0.3 intent_multiplier = 0.35 + intensity * 0.25 + avg_ctr * 9.5 projected_revenue = round( listing.price_usd * listing.commission_rate * volume_estimate * buy_box_lift * prime_lift * confidence_lift * intent_multiplier / 100, 2, ) if keyword_overlap: rationale = ( f"Aligns {listing.category.lower()} offer with {', '.join(keyword_overlap)} demand signals." ) else: rationale = ( f"High rating and volume listing positioned for {listing.category.lower()} expansion." ) source = "amazon_paapi" if self._session else "amazon_catalog" notes = None if not self._session: notes = ( "Simulated listing intelligence; supply Amazon PA-API credentials to activate live harvesting." ) recommendations.append( AmazonProductRecommendation( asin=listing.asin, title=listing.title, category=listing.category, price_usd=listing.price_usd, commission_rate=listing.commission_rate, rating=listing.rating, reviews=listing.reviews, estimated_monthly_sales=listing.estimated_monthly_sales, buy_box_share=listing.buy_box_share, prime_eligible=listing.prime_eligible, fulfillment_model=listing.fulfillment_model, projected_monthly_revenue=projected_revenue, rationale=rationale, url=listing.url, source=source, notes=notes, ) ) return recommendations @dataclass(slots=True) class EbayMarketplaceListing: """eBay marketplace listing metadata for revenue planning.""" item_id: str title: str category: str price_usd: float affiliate_rate: float seller_level: str seller_rating: float conversion_rate: float sold_per_month: int shipping_days: int playbook: List[str] confidence: float @dataclass(slots=True) class CJAffiliateOffer: """Offer metadata sourced from the Commission Junction catalog.""" program_name: str advertiser_id: str category: str commission_rate: float epc: float seven_day_epc: float network_rank: int payout_terms: str landing_url: str description: str keywords: List[str] @dataclass(slots=True) class CJAffiliateRecommendation: """Recommendation returned by the CJ affiliate process.""" program_name: str advertiser_id: str category: str commission_rate: float epc: float seven_day_epc: float projected_epc: float projected_monthly_revenue: float network_rank: int payout_terms: str landing_url: str rationale: str source: str notes: str | None = None @dataclass(slots=True) class AmazonMarketplaceListing: """Amazon or AWS Marketplace listing metadata.""" asin: str title: str category: str price_usd: float commission_rate: float rating: float reviews: int url: str keywords: List[str] @dataclass(slots=True) class EbayRevenuePlay: """Recommendation payload produced by the eBay marketplace process.""" item_id: str title: str category: str price_usd: float affiliate_rate: float seller_level: str seller_rating: float conversion_rate: float sold_per_month: int projected_monthly_revenue: float projected_profit_margin: float shipping_days: int class AmazonProductRecommendation: """Recommendation payload produced by the Amazon marketplace process.""" asin: str title: str category: str price_usd: float commission_rate: float rating: float reviews: int projected_monthly_revenue: float rationale: str url: str source: str notes: str | None = None class EbayMarketplaceCatalog: """Loads curated eBay marketplace listings for offline use.""" def __init__(self, listings: Sequence[EbayMarketplaceListing] | None = None): if listings is not None: self._listings = list(listings) else: with open(EBAY_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle: data = json.load(handle) self._listings = [EbayMarketplaceListing(**entry) for entry in data] def match_listings( self, tokens: Sequence[str], limit: int, focus: str | None = None ) -> List[Tuple[float, EbayMarketplaceListing]]: ranked: List[Tuple[float, EbayMarketplaceListing]] = [] token_set = {token.lower() for token in tokens} for listing in self._listings: haystack = ( f"{listing.title} {listing.category} {' '.join(listing.keywords)}" ).lower() class AmazonMarketplaceCatalog: """Loads curated Amazon and AWS marketplace listings for offline use.""" def __init__(self, listings: Sequence[AmazonMarketplaceListing] | None = None): if listings is not None: self._listings = list(listings) else: with open(AMAZON_MARKETPLACE_DATASET, "r", encoding="utf-8") as handle: data = json.load(handle) self._listings = [AmazonMarketplaceListing(**entry) for entry in data] def match_listings( self, tokens: Sequence[str], limit: int, focus: str | None = None ) -> List[Tuple[float, AmazonMarketplaceListing]]: ranked: List[Tuple[float, AmazonMarketplaceListing]] = [] token_set = {token.lower() for token in tokens} for listing in self._listings: haystack = f"{listing.title} {listing.category} {' '.join(listing.keywords)}".lower() score = 0.0 keyword_hits = 0 for token in token_set: if token in haystack: score += 1.4 keyword_hits += 1 if token in {keyword.lower() for keyword in listing.keywords}: score += 1.6 if focus: focus_lower = focus.lower() if focus_lower in listing.category.lower(): score += 1.0 if focus_lower in haystack: score += 0.6 score += min(listing.seller_rating / 5.0, 1.0) score += min(listing.conversion_rate * 80.0, 1.2) score += min(listing.sold_per_month / 350.0, 1.2) if listing.seller_level.lower().startswith("top"): score += 0.35 if listing.shipping_days <= 3: score += 0.25 score += 1.5 keyword_hits += 1 if token in {keyword.lower() for keyword in listing.keywords}: score += 1.8 if focus: if focus.lower() in listing.category.lower(): score += 1.2 if focus.lower() in haystack: score += 0.8 score += min(listing.rating / 5.0, 1.0) score += min(listing.reviews / 500.0, 1.0) score += keyword_hits * 0.1 ranked.append((score, listing)) ranked.sort(key=lambda item: item[0], reverse=True) return ranked[: max(1, limit)] class EbayMarketplaceProcess: """Transforms eBay inventory into performance-driven affiliate plays.""" REQUIRED_ENV_VARS = { "EBAY_APP_ID": "app_id", "EBAY_CERT_ID": "cert_id", "EBAY_DEV_ID": "dev_id", } OPTIONAL_ENV_VARS = { "EBAY_REDIRECT_URI": "redirect_uri", "EBAY_CAMPAIGN_ID": "campaign_id", class AmazonMarketplaceProcess: """Transforms marketplace listings into revenue plans with optional SDK enrichment.""" REQUIRED_ENV_VARS = { "AMAZON_PAAPI_ACCESS_KEY": "access_key", "AMAZON_PAAPI_SECRET_KEY": "[credential removed]", "AMAZON_PAAPI_PARTNER_TAG": "partner_tag", } OPTIONAL_ENV_VARS = { "AWS_REGION": "region", "AWS_PROFILE": "profile", } def __init__( self, catalog: EbayMarketplaceCatalog | None = None, config: Dict[str, Any] | None = None, ) -> None: self._catalog = catalog or EbayMarketplaceCatalog() catalog: AmazonMarketplaceCatalog | None = None, config: Dict[str, Any] | None = None, ) -> None: self._catalog = catalog or AmazonMarketplaceCatalog() self._config = config or self._config_from_env() self._session = self._build_session() def _build_session(self) -> Any | None: if not self.configured or requests is None: return None try: session = requests.Session() session.headers.update({"User-Agent": "ai-brain-marketing-ani/1.0"}) return session if not self.configured or boto3 is None: return None try: # pragma: no cover - requires boto3 dependency return boto3.session.Session( aws_access_key_id=self._config.get("access_key"), aws_secret_access_key=[credential removed]"secret_key"), region_name=self._config.get("region"), profile_name=self._config.get("profile"), ) except Exception: return None @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in {**cls.REQUIRED_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items(): value = os.getenv(env_var) if value: config[key] = value return config @property def configured(self) -> bool: required = {key for key in self.REQUIRED_ENV_VARS.values()} return required <= self._config.keys() def listings( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[EbayRevenuePlay]: ) -> List[AmazonProductRecommendation]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) focus = None if campaigns: focus = campaigns[0].campaign.channel.split()[0] matches = self._catalog.match_listings(tokens, limit, focus) if not matches: return [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.0 avg_confidence = ( mean([score.metrics.confidence for score in campaigns]) if campaigns else 0.5 ) recommendations: List[EbayRevenuePlay] = [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.1 avg_ctr = mean([score.metrics.expected_ctr for score in campaigns]) if campaigns else 0.025 recommendations: List[AmazonProductRecommendation] = [] for match_score, listing in matches: keyword_overlap = sorted( { token for token in tokens if token in {kw.lower() for kw in listing.keywords} or token in listing.title.lower() } ) intensity = max(0.2, min(2.2, match_score / 3.8)) velocity = listing.sold_per_month * max(0.45, avg_roi / 2.2) conversion_lift = 0.6 + listing.conversion_rate * 14.0 seller_lift = 0.8 + (listing.seller_rating / 5.0) * 0.4 speed_lift = 1.05 + max(0, (4 - listing.shipping_days)) * 0.04 confidence_lift = 0.8 + avg_confidence * 0.35 projected_revenue = round( listing.price_usd * listing.affiliate_rate * velocity * conversion_lift * seller_lift * speed_lift * confidence_lift * intensity / 100, 2, ) projected_margin = round( min(0.92, listing.affiliate_rate * (conversion_lift * 0.6 + 0.35)), 2, ) if keyword_overlap: rationale = ( f"Targets {', '.join(keyword_overlap)} buyers with proven conversion velocity." ) else: rationale = ( f"Top-rated {listing.category.lower()} seller with accelerated sell-through momentum." ) source = "ebay_partner_api" if self._session else "ebay_catalog" notes = None if not self._session: notes = ( "Offline catalog heuristics; supply eBay developer credentials to activate live sourcing." ) recommendations.append( EbayRevenuePlay( item_id=listing.item_id, title=listing.title, category=listing.category, price_usd=listing.price_usd, affiliate_rate=listing.affiliate_rate, seller_level=listing.seller_level, seller_rating=listing.seller_rating, conversion_rate=listing.conversion_rate, sold_per_month=listing.sold_per_month, projected_monthly_revenue=projected_revenue, projected_profit_margin=projected_margin, shipping_days=listing.shipping_days, intensity = max(0.1, min(2.0, match_score / 4.0)) demand_factor = max(75.0, avg_roi * 45.0 + avg_ctr * 1200) projected_revenue = round( listing.price_usd * listing.commission_rate * demand_factor * (0.3 + intensity * 0.2) / 100, 2, ) if keyword_overlap: rationale = ( f"Aligns {listing.category.lower()} offer with {', '.join(keyword_overlap)} demand signals." ) else: rationale = ( f"High rating and volume listing positioned for {listing.category.lower()} expansion." ) source = "amazon_paapi" if self._session else "amazon_catalog" notes = None if not self._session: notes = ( "Simulated listing intelligence; supply Amazon PA-API credentials to activate live harvesting." ) recommendations.append( AmazonProductRecommendation( asin=listing.asin, title=listing.title, category=listing.category, price_usd=listing.price_usd, commission_rate=listing.commission_rate, rating=listing.rating, reviews=listing.reviews, projected_monthly_revenue=projected_revenue, rationale=rationale, url=listing.url, source=source, notes=notes, ) ) return recommendations @dataclass(slots=True) class CryptoMarketSnapshot: """Market intelligence payload for a cryptocurrency asset.""" asset: str price_usd: float | None change_24h: float | None market_cap: float | None volume_24h: float | None source: str notes: str | None = None class CryptoMarketProcess: """Ingests crypto market data across public APIs with graceful fallbacks.""" ASSET_ALIASES: Dict[str, str] = { "btc": "bitcoin", "bitcoin": "bitcoin", "sats": "bitcoin", "eth": "ethereum", "ethereum": "ethereum", "sol": "solana", "solana": "solana", "matic": "polygon", "polygon": "polygon", "doge": "dogecoin", "dogecoin": "dogecoin", } DEFAULT_ASSETS: List[str] = ["bitcoin", "ethereum", "solana"] FALLBACK_PRICES: Dict[str, Dict[str, Any]] = { "bitcoin": { "price_usd": 68000.0, "change_24h": 2.5, "market_cap": 1.3e12, "volume_24h": 3.1e10, "source": "simulated", "notes": "Use CoinGecko or CoinCap credentials for live BTC spot feeds.", }, "ethereum": { "price_usd": 3500.0, "change_24h": 3.1, "market_cap": 4.2e11, "volume_24h": 1.8e10, "source": "simulated", "notes": "Hook CoinGecko or CoinCap to mirror ETH market structure.", }, "solana": { "price_usd": 160.0, "change_24h": 4.8, "market_cap": 7.2e10, "volume_24h": 4.1e9, "source": "simulated", "notes": "Pair CoinGecko streams for SOL liquidity snapshots.", }, "polygon": { "price_usd": 0.95, "change_24h": 1.2, "market_cap": 8.8e9, "volume_24h": 6.7e8, "source": "simulated", "notes": "Integrate CoinCap assets endpoint for live Polygon metrics.", }, "dogecoin": { "price_usd": 0.18, "change_24h": 5.5, "market_cap": 2.6e10, "volume_24h": 9.2e8, "source": "simulated", "notes": "CoinGecko provides DOGE spot pricing with rate-limited tier.", }, } def __init__( self, session: Any | None = None, timeout: float = 4.0, allow_network: bool = True, ) -> None: self._session = None if allow_network and requests is not None: self._session = session or requests.Session() self._timeout = timeout @property def configured(self) -> bool: return self._session is not None def _normalize_asset(self, token: str) -> str | None: return self.ASSET_ALIASES.get(token.lower()) def _infer_assets(self, prompt: str, limit: int) -> List[str]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) assets: List[str] = [] for token in tokens: asset = self._normalize_asset(token) if asset and asset not in assets: assets.append(asset) for asset in self.DEFAULT_ASSETS: if asset not in assets: assets.append(asset) return assets[: max(1, limit)] def _request_json( self, url: str, params: Dict[str, Any] | None = None ) -> Dict[str, Any] | List[Any] | None: if not self._session: return None try: # pragma: no cover - requires network response = self._session.get(url, params=params, timeout=self._timeout) response.raise_for_status() return response.json() except Exception: return None def _fetch_coingecko(self, asset: str) -> Dict[str, Any] | None: data = self._request_json( "https://api.coingecko.com/api/v3/simple/price", params={ "ids": asset, "vs_currencies": "usd", "include_24hr_change": "true", "include_market_cap": "true", "include_24hr_vol": "true", }, ) if isinstance(data, dict) and asset in data: entry = data[asset] return { "price_usd": float(entry.get("usd")) if entry.get("usd") is not None else None, "change_24h": float(entry.get("usd_24h_change")) if entry.get("usd_24h_change") is not None else None, "market_cap": float(entry.get("usd_market_cap")) if entry.get("usd_market_cap") is not None else None, "volume_24h": float(entry.get("usd_24h_vol")) if entry.get("usd_24h_vol") is not None else None, "source": "coingecko", } return None def _fetch_coincap(self, asset: str) -> Dict[str, Any] | None: data = self._request_json(f"https://api.coincap.io/v2/assets/{asset}") if isinstance(data, dict) and isinstance(data.get("data"), dict): entry = data["data"] try: price = float(entry.get("priceUsd")) if entry.get("priceUsd") is not None else None change = float(entry.get("changePercent24Hr")) if entry.get("changePercent24Hr") is not None else None market_cap = float(entry.get("marketCapUsd")) if entry.get("marketCapUsd") is not None else None volume = float(entry.get("volumeUsd24Hr")) if entry.get("volumeUsd24Hr") is not None else None except (TypeError, ValueError): price = change = market_cap = volume = None return { "price_usd": price, "change_24h": change, "market_cap": market_cap, "volume_24h": volume, "source": "coincap", } return None def _fetch_blockstream(self) -> str | None: data = self._request_json("https://blockstream.info/api/mempool") if isinstance(data, dict) and {"count", "vsize"} <= data.keys(): return f"Blockstream mempool: {data['count']} txs, {data['vsize']} vsize" return None def _fetch_blockcypher(self, asset: str) -> str | None: if asset != "bitcoin": return None data = self._request_json("https://api.blockcypher.com/v1/btc/main") if isinstance(data, dict) and {"height", "unconfirmed_count"} <= data.keys(): return ( "BlockCypher height " f"{data['height']} with {data['unconfirmed_count']} unconfirmed tx" ) return None def market_data(self, prompt: str, limit: int = 3) -> List[CryptoMarketSnapshot]: assets = self._infer_assets(prompt, limit) snapshots: List[CryptoMarketSnapshot] = [] blockstream_note = self._fetch_blockstream() for asset in assets: payload = self._fetch_coingecko(asset) or self._fetch_coincap(asset) if payload is None: fallback = self.FALLBACK_PRICES.get(asset) or self.FALLBACK_PRICES["bitcoin"] payload = dict(fallback) else: payload = dict(payload) source = payload.pop("source", "simulated") notes = payload.pop("notes", None) chain_note = self._fetch_blockcypher(asset) combined_notes = " | ".join( note for note in [notes, blockstream_note if asset == "bitcoin" else None, chain_note] if note ) snapshots.append( CryptoMarketSnapshot( asset=asset, price_usd=payload.get("price_usd"), change_24h=payload.get("change_24h"), market_cap=payload.get("market_cap"), volume_24h=payload.get("volume_24h"), source=source, notes=combined_notes or None, ) ) return snapshots @dataclass(slots=True) class AWSRevenueProgram: """AWS program metadata for revenue acceleration.""" program_name: str focus: str description: str revenue_motion: str primary_service: str secondary_services: List[str] automation_play: str base_roi: float focus_keywords: List[str] @dataclass(slots=True) class AWSRevenueRecommendation: """Recommendation payload produced by the AWS revenue process.""" program_name: str focus: str description: str revenue_motion: str primary_service: str secondary_services: List[str] automation_play: str projected_roi: float source: str notes: str | None = None class AWSGrowthPlaybookCatalog: """Loads AWS growth programs and matches them to prompts.""" def __init__(self, programs: Sequence[AWSRevenueProgram] | None = None): if programs is not None: self._programs = list(programs) else: with open(AWS_GROWTH_PLAYBOOKS, "r", encoding="utf-8") as handle: data = json.load(handle) self._programs = [AWSRevenueProgram(**entry) for entry in data] def match_programs( self, tokens: Sequence[str], limit: int ) -> List[Tuple[float, AWSRevenueProgram]]: ranked: List[Tuple[float, AWSRevenueProgram]] = [] token_set = {token.lower() for token in tokens} for program in self._programs: haystack = ( f"{program.program_name} {program.description} {program.revenue_motion} " f"{program.primary_service} {' '.join(program.secondary_services)}" ).lower() score = 0.0 for token in token_set: if token in haystack: score += 1.2 if token in {kw.lower() for kw in program.focus_keywords}: score += 1.6 if program.focus in token_set: score += 0.5 ranked.append((score, program)) ranked.sort(key=lambda item: item[0], reverse=True) return ranked[: max(1, limit)] class AWSRevenueProcess: """Generates AWS-backed revenue motions and optionally validates via boto3.""" REQUIRED_ENV_VARS = { "AWS_ACCESS_KEY_ID": "access_key_id", "AWS_SECRET_ACCESS_KEY": "[credential removed]", } OPTIONAL_ENV_VARS = { "AWS_SESSION_TOKEN": "session_token", "AWS_REGION": "region", "AWS_PROFILE": "profile", } def __init__( self, catalog: AWSGrowthPlaybookCatalog | None = None, config: Dict[str, Any] | None = None, ) -> None: self._catalog = catalog or AWSGrowthPlaybookCatalog() self._config = config or self._config_from_env() self._session = self._build_session() def _build_session(self) -> Any | None: if not self.configured or boto3 is None: return None try: # pragma: no cover - requires boto3 dependency return boto3.session.Session( aws_access_key_id=self._config.get("access_key_id"), aws_secret_access_key=[credential removed]"secret_access_key"), aws_session_token=self._config.get("session_token"), region_name=self._config.get("region"), profile_name=self._config.get("profile"), ) except Exception: return None @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in {**cls.REQUIRED_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items(): value = os.getenv(env_var) if value: config[key] = value return config @property def configured(self) -> bool: required = {key for key in self.REQUIRED_ENV_VARS.values()} return required <= self._config.keys() def plays( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[AWSRevenueRecommendation]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) matches = self._catalog.match_programs(tokens, limit) if not matches: return [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.5 avg_conf = mean([score.metrics.confidence for score in campaigns]) if campaigns else 0.65 recommendations: List[AWSRevenueRecommendation] = [] for match_score, program in matches: projected_roi = round( program.base_roi + match_score * 0.2 + max(0.0, avg_roi - 2.0) * 0.15, 2, ) projected_roi = max(projected_roi, program.base_roi) rationale = ( f"Leverage {program.primary_service} with {', '.join(program.secondary_services)} " f"to execute {program.revenue_motion.lower()}" ) notes = None if not self._session: notes = ( "Offline AWS growth playbooks active; configure AWS credentials to validate deployment." ) recommendations.append( AWSRevenueRecommendation( program_name=program.program_name, focus=program.focus, description=program.description, revenue_motion=program.revenue_motion, primary_service=program.primary_service, secondary_services=program.secondary_services, automation_play=program.automation_play, projected_roi=max(projected_roi, avg_conf * program.base_roi), source="aws_sdk" if self._session else "aws_playbooks", notes=notes, ) ) return recommendations class BudgetAllocatorProcess: """Turns campaign rankings into channel-level budget plans.""" def __init__( self, profiles: Sequence[BudgetProfile] | None = None, dataset_path: str = CHANNEL_INVESTMENTS_DATASET, default_budget: float = 25000.0, ): self._profiles = list(profiles) if profiles is not None else self._profiles_from_file(dataset_path) self._default_budget = default_budget @staticmethod def _profiles_from_file(path: str) -> List[BudgetProfile]: try: with open(path, "r", encoding="utf-8") as handle: payload = json.load(handle) except FileNotFoundError: payload = {"profiles": []} profiles: List[BudgetProfile] = [] for entry in payload.get("profiles", []): profiles.append( BudgetProfile( channel=entry.get("channel", "Integrated Marketing"), keywords=[keyword.lower() for keyword in entry.get("keywords", [])], baseline_cpc=float(entry.get("baseline_cpc", 4.0)), baseline_cpl=float(entry.get("baseline_cpl", 150.0)), avg_conversion_rate=float(entry.get("avg_conversion_rate", 0.045)), avg_roi=float(entry.get("avg_roi", 3.2)), recommended_monthly_spend=float(entry.get("recommended_monthly_spend", 20000.0)), ) ) if not profiles: profiles.append( BudgetProfile( channel="Integrated Marketing", keywords=["integrated", "multi-channel"], baseline_cpc=4.0, baseline_cpl=150.0, avg_conversion_rate=0.045, avg_roi=3.0, recommended_monthly_spend=20000.0, ) ) return profiles def _match_profile(self, channel: str) -> BudgetProfile: lowered = channel.lower() best: BudgetProfile | None = None best_score = -1 for profile in self._profiles: score = 0 if profile.channel.lower() in lowered: score += 3 for keyword in profile.keywords: if keyword in lowered: score += 1 if score > best_score: best = profile best_score = score if best is None: best = BudgetProfile( channel=channel, keywords=[channel.lower()], baseline_cpc=4.5, baseline_cpl=165.0, avg_conversion_rate=0.042, avg_roi=3.1, recommended_monthly_spend=self._default_budget, ) return best @staticmethod def _parse_budget_from_prompt(prompt: str) -> float | None: pattern = re.compile(r"\$?([0-9][0-9,]*)(?:\s*(k|m|b|million|billion|thousand))?", re.IGNORECASE) matches = pattern.findall(prompt) if not matches: return None inferred: List[float] = [] for value_str, multiplier in matches: value = float(value_str.replace(",", "")) if multiplier: token = multiplier.lower() if token in {"k", "thousand"}: value *= 1_000 elif token in {"m", "million"}: value *= 1_000_000 elif token in {"b", "billion"}: value *= 1_000_000_000 elif value < 100: value *= 1_000 inferred.append(value) return max(inferred) if inferred else None def _infer_budget(self, prompt: str, profiles: Sequence[BudgetProfile]) -> float: parsed = self._parse_budget_from_prompt(prompt) if parsed is not None and parsed > 0: return float(parsed) if profiles: average_spend = mean(profile.recommended_monthly_spend for profile in profiles) return float(max(average_spend, self._default_budget)) return self._default_budget @staticmethod def _allocation_weight(score: CampaignScore, profile: BudgetProfile) -> float: roi_component = score.metrics.expected_roi * 0.45 ctr_component = score.metrics.expected_ctr * 100.0 * 0.2 profile_component = profile.avg_roi * 0.25 efficiency_component = 240.0 / max(profile.baseline_cpl, 60.0) return max(0.1, roi_component + ctr_component + profile_component + efficiency_component) @staticmethod def _summarize_plan(budget: float, expected_revenue: float, count: int) -> str: if budget <= 0 or expected_revenue <= 0: return "No budgetable campaigns identified." roi = expected_revenue / budget if budget else 0 return ( f"Deploy ${budget:,.0f} across {count} channels targeting ~${expected_revenue:,.0f} revenue " f"(~{roi:.1f}x ROI)." ) @staticmethod def _payback_weeks(budget: float, expected_revenue: float) -> float: profit = expected_revenue - budget if budget <= 0: return 0.0 if profit <= 0: return 16.0 weeks = (budget / profit) * 4 return round(max(2.0, min(26.0, weeks)), 1) def plan( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int = 3, ) -> BudgetPlan: if not campaigns: raise ValueError("plan requires at least one campaign score") selected = list(campaigns[: max(1, limit)]) profiles = [self._match_profile(score.campaign.channel) for score in selected] total_budget = self._infer_budget(prompt, profiles) weighted: List[Tuple[CampaignScore, BudgetProfile, float]] = [] for score, profile in zip(selected, profiles): weight = self._allocation_weight(score, profile) weighted.append((score, profile, weight)) total_weight = sum(entry[2] for entry in weighted) allocations: List[BudgetAllocation] = [] running_total = 0.0 for index, (score, profile, weight) in enumerate(weighted): share = weight / total_weight if total_weight else 1.0 / len(weighted) allocation = round(total_budget * share, 2) if index == len(weighted) - 1: allocation = round(total_budget - running_total, 2) running_total += allocation expected_leads = round(allocation / max(profile.baseline_cpl, 1.0), 1) blended_roi = max(1.05, (score.metrics.expected_roi + profile.avg_roi) / 2) expected_revenue = round(allocation * blended_roi, 2) rationale = ( f"Amplify {score.campaign.channel} for {score.campaign.audience} to accelerate " f"{score.campaign.objective}." ) notes = None if profile.channel.lower() not in score.campaign.channel.lower(): notes = ( f"Mapped to {profile.channel} benchmarks using keyword similarity; override dataset " "to tune allocation." ) allocations.append( BudgetAllocation( channel=score.campaign.channel, audience_focus=score.campaign.audience, offer=score.campaign.offer, objective=score.campaign.objective, allocation_usd=allocation, allocation_weight=round(share, 3), expected_leads=expected_leads, expected_revenue=expected_revenue, rationale=rationale, source="budget_optimizer", notes=notes, ) ) total_expected_revenue = round(sum(entry.expected_revenue for entry in allocations), 2) expected_roi = round(total_expected_revenue / total_budget, 2) if total_budget else 0.0 payback_weeks = self._payback_weeks(total_budget, total_expected_revenue) summary = self._summarize_plan(total_budget, total_expected_revenue, len(allocations)) return BudgetPlan( total_budget=round(total_budget, 2), allocations=allocations, expected_revenue=total_expected_revenue, expected_roi=expected_roi, payback_period_weeks=payback_weeks, summary=summary, ) @dataclass(slots=True) class GoogleCampaignPerformance: """Performance snapshot surfaced from the Google Ads API.""" campaign_name: str clicks: int impressions: int conversions: float cost_micros: int ctr: float cpc: float roas: float source: str notes: str | None = None @dataclass(slots=True) class StripeMonetizationPlan: """Stripe checkout strategy synthesized from campaign intelligence.""" product_name: str price_usd: float billing_interval: str currency: str rationale: str setup_steps: List[str] source: str notes: str | None = None class StripeProcess: """Shapes campaign ideas into Stripe-ready monetization workflows.""" def __init__(self, api_key: str | None = None, account_id: str | None = None) -> None: self._api_key = [credential removed] or os.getenv("STRIPE_API_KEY") self._account_id = account_id or os.getenv("STRIPE_ACCOUNT_ID") self._configured = bool(stripe is not None and self._api_key) if self._configured and stripe is not None: # pragma: no cover - requires SDK stripe.api_key = [credential removed] @property def configured(self) -> bool: return self._configured def _infer_billing_interval(self, prompt: str) -> str: lowered = prompt.lower() subscription_keywords = { "subscription", "recurring", "membership", "retainer", "saas", } if any(keyword in lowered for keyword in subscription_keywords): return "monthly" if "annual" in lowered or "yearly" in lowered: return "annual" return "one_time" def plans( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int = 3, ) -> List[StripeMonetizationPlan]: if not campaigns: raise ValueError("Stripe plans require at least one campaign score") interval = self._infer_billing_interval(prompt) plans: List[StripeMonetizationPlan] = [] for scored in campaigns[: max(1, limit)]: base_price = max(29.0, scored.metrics.expected_roi * 45) audience = scored.campaign.audience.lower() if "enterprise" in audience: base_price *= 1.6 elif "consumer" in audience: base_price *= 0.75 if interval == "annual": base_price *= 10.5 elif interval == "one_time": base_price *= 1.25 price = round(base_price, 2) rationale = ( f"Stripe-ready {interval.replace('_', ' ')} offer leveraging {scored.campaign.channel} " f"for {scored.campaign.audience}." ) if scored.metrics.confidence < 0.5: rationale += " Calibrate pricing with phased rollout given confidence score." setup_steps = [ "Create Product in Stripe aligned to the campaign offer.", "Attach a Price with the recommended interval and USD currency.", "Launch via Stripe Checkout or Payment Links to validate demand.", ] if interval != "one_time": setup_steps.append("Enable subscription trials and dunning automations.") else: setup_steps.append("Automate follow-up journeys via Stripe Webhooks or customer portal.") source = "stripe_sdk" if self._configured else "simulated" notes = None if not self._configured: notes = ( "Install the official stripe SDK and export STRIPE_API_KEY/STRIPE_ACCOUNT_ID " "to activate live checkout orchestration." ) plans.append( StripeMonetizationPlan( product_name=f"{scored.campaign.offer.title()} Checkout", price_usd=price, billing_interval=interval, currency="usd", rationale=rationale, setup_steps=setup_steps, source=source, notes=notes, ) ) return plans @dataclass(slots=True) class PayPalMonetizationPlan: """PayPal commerce strategy to operationalize campaign monetization.""" product_name: str price_usd: float checkout_flow: str payout_schedule: str rationale: str setup_steps: List[str] source: str notes: str | None = None class PayPalProcess: """Designs PayPal-ready offers so campaigns translate into paychecks.""" def __init__( self, client_id: str | None = None, client_secret: str | None = None, merchant_id: str | None = None, environment: str | None = None, ) -> None: self._client_id = client_id or os.getenv("PAYPAL_CLIENT_ID") self._client_secret = [credential removed] or os.getenv("PAYPAL_CLIENT_SECRET") self._merchant_id = merchant_id or os.getenv("PAYPAL_MERCHANT_ID") self._environment = (environment or os.getenv("PAYPAL_ENVIRONMENT", "sandbox")).lower() self._configured = bool( PayPalHttpClient is not None and self._client_id and self._client_secret ) self._client: PayPalHttpClient | None = None if self._configured and PayPalHttpClient is not None: # pragma: no cover - requires SDK if self._environment in {"live", "production"} and LiveEnvironment is not None: env = LiveEnvironment(self._client_id, self._client_secret) else: env = SandboxEnvironment(self._client_id, self._client_secret) self._client = PayPalHttpClient(env) @property def configured(self) -> bool: return self._configured def _infer_checkout_flow(self, prompt: str) -> str: lowered = prompt.lower() if any(keyword in lowered for keyword in ["subscription", "membership", "recurring"]): return "subscription" if any(keyword in lowered for keyword in ["invoice", "retainer", "contract"]): return "invoice" return "one_time" def _infer_payout_schedule(self, prompt: str) -> str: lowered = prompt.lower() if any(keyword in lowered for keyword in ["daily", "paycheck", "cash flow"]): return "daily" if any(keyword in lowered for keyword in ["weekly", "bi-weekly", "payout"]): return "weekly" return "rolling" def plans( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int = 3, ) -> List[PayPalMonetizationPlan]: if not campaigns: raise ValueError("PayPal plans require at least one campaign score") flow = self._infer_checkout_flow(prompt) payout_schedule = self._infer_payout_schedule(prompt) plans: List[PayPalMonetizationPlan] = [] for scored in campaigns[: max(1, limit)]: base_price = max(19.0, scored.metrics.expected_roi * 35) if "enterprise" in scored.campaign.audience.lower(): base_price *= 1.4 elif "consumer" in scored.campaign.audience.lower(): base_price *= 0.8 if flow == "subscription": base_price *= 9.5 elif flow == "invoice": base_price *= 4.5 price = round(base_price, 2) rationale = ( f"PayPal {flow.replace('_', ' ')} monetization aligned to {scored.campaign.channel} " f"for {scored.campaign.audience}." ) if payout_schedule == "daily": rationale += " Configured for accelerated daily paychecks." setup_steps = [ "Create Product or Plan in PayPal matching the campaign offer.", f"Configure {flow} checkout with contextual upsells.", f"Enable payouts on a {payout_schedule} cadence for predictable cashflow.", ] if self._merchant_id: setup_steps.append( f"Link merchant account {self._merchant_id} to PayPal Payouts for revenue capture." ) else: setup_steps.append("Map payouts to finance workflows for accounting reconciliation.") source = "paypal_sdk" if self._configured else "simulated" notes = None if not self._configured: notes = ( "Install paypalcheckoutsdk and export PAYPAL_CLIENT_ID/PAYPAL_CLIENT_SECRET " "to activate live PayPal revenue collection." ) plans.append( PayPalMonetizationPlan( product_name=f"{scored.campaign.offer.title()} PayPal Flow", price_usd=price, checkout_flow=flow, payout_schedule=payout_schedule, if scored.metrics.confidence < 0.5: rationale += " Calibrate pricing with phased rollout given confidence score." setup_steps = [ "Create Product in Stripe aligned to the campaign offer.", "Attach a Price with the recommended interval and USD currency.", "Launch via Stripe Checkout or Payment Links to validate demand.", ] if interval != "one_time": setup_steps.append("Enable subscription trials and dunning automations.") else: setup_steps.append("Automate follow-up journeys via Stripe Webhooks or customer portal.") source = "stripe_sdk" if self._configured else "simulated" notes = None if not self._configured: notes = ( "Install the official stripe SDK and export STRIPE_API_KEY/STRIPE_ACCOUNT_ID " "to activate live checkout orchestration." ) plans.append( StripeMonetizationPlan( product_name=f"{scored.campaign.offer.title()} Checkout", price_usd=price, billing_interval=interval, currency="usd", rationale=rationale, setup_steps=setup_steps, source=source, notes=notes, ) ) return plans class GoogleAdsProcess: """Bridges the Google Ads API to enrich ANI recommendations.""" REQUIRED_ENV_VARS = { "GOOGLE_ADS_DEVELOPER_TOKEN": "developer_token", "GOOGLE_ADS_CUSTOMER_ID": "customer_id", } OAUTH_ENV_VARS = { "GOOGLE_ADS_CLIENT_ID": "client_id", "GOOGLE_ADS_CLIENT_SECRET": "[credential removed]", "GOOGLE_ADS_REFRESH_TOKEN": "refresh_token", } OPTIONAL_ENV_VARS = { "GOOGLE_ADS_LOGIN_CUSTOMER_ID": "login_customer_id", } SERVICE_ACCOUNT_ENV_VARS = { "GOOGLE_ADS_SERVICE_ACCOUNT_INFO": "service_account_info", "GOOGLE_ADS_SERVICE_ACCOUNT_FILE": "service_account_file", "GOOGLE_ADS_SERVICE_ACCOUNT_B64": "service_account_b64", "GOOGLE_APPLICATION_CREDENTIALS": "service_account_file", } def __init__(self, config: Dict[str, Any] | None = None): self._config = config or self._config_from_env() self._client = self._build_client(self._config) @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in cls.REQUIRED_ENV_VARS.items(): value = os.getenv(env_var) if value: config[key] = value for env_var, key in {**cls.OAUTH_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items(): value = os.getenv(env_var) if value: config[key] = value for env_var, key in cls.SERVICE_ACCOUNT_ENV_VARS.items(): value = os.getenv(env_var) if not value: continue if key == "service_account_b64": try: decoded = base64.b64decode(value).decode("utf-8") config["service_account_info"] = json.loads(decoded) except (ValueError, json.JSONDecodeError): continue elif key == "service_account_file": try: with open(value, "r", encoding="utf-8") as handle: config["service_account_info"] = json.load(handle) except (FileNotFoundError, json.JSONDecodeError, OSError): continue elif key == "service_account_info": try: config["service_account_info"] = json.loads(value) except json.JSONDecodeError: continue return config @staticmethod def _build_client(config: Dict[str, Any]) -> GoogleAdsClient | None: if not config or "customer_id" not in config: return None if GoogleAdsClient is None: return None try: # pragma: no cover - relies on network credentials to execute credentials = None if config.get("service_account_info") and service_account is not None: info = config["service_account_info"] if isinstance(info, str): try: info = json.loads(info) except json.JSONDecodeError: info = None if isinstance(info, dict): scopes = ["https://www.googleapis.com/auth/adwords"] credentials = service_account.Credentials.from_service_account_info( info, scopes=scopes ) client_kwargs = { "developer_token": config.get("developer_token"), "login_customer_id": config.get("login_customer_id"), "use_proto_plus": True, } if credentials is not None: return GoogleAdsClient.load_from_dict(client_kwargs, credentials=credentials) # Fallback to OAuth credential set when present if all(config.get(field) for field in ("client_id", "client_secret", "refresh_token")): client_kwargs.update( { "client_id": config.get("client_id"), "client_secret": config.get("client_secret"), "refresh_token": config.get("refresh_token"), } ) return GoogleAdsClient.load_from_dict(client_kwargs) except Exception: # pragma: no cover - fallback handled downstream return None @property def configured(self) -> bool: return bool(self._client) def performance( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[GoogleCampaignPerformance]: limit = max(1, limit) if self._client is None: return self._simulate(prompt, campaigns, limit) try: # pragma: no cover - executed when Google Ads credentials available ga_service = self._client.get_service("GoogleAdsService") query = self._build_query(limit) response = ga_service.search( customer_id=self._config.get("customer_id"), query=query, ) insights: List[GoogleCampaignPerformance] = [] for row in response: metrics = row.metrics campaign = row.campaign clicks = int(getattr(metrics, "clicks", 0)) impressions = int(getattr(metrics, "impressions", 0)) conversions = float(getattr(metrics, "conversions", 0.0)) cost_micros = int(getattr(metrics, "cost_micros", 0)) ctr = float(getattr(metrics, "ctr", 0.0)) cpc = float(getattr(metrics, "average_cpc", 0.0)) roas = float(getattr(metrics, "conversions_value_per_cost", 0.0)) insights.append( GoogleCampaignPerformance( campaign_name=getattr(campaign, "name", "Campaign"), clicks=clicks, impressions=impressions, conversions=conversions, cost_micros=cost_micros, ctr=ctr, cpc=cpc, roas=roas, source="google_ads_api", notes="Live Google Ads data", ) ) if insights: return insights except Exception: # pragma: no cover - gracefully fallback on API errors pass return self._simulate(prompt, campaigns, limit) @staticmethod def _build_query(limit: int) -> str: return ( "SELECT campaign.name, metrics.clicks, metrics.impressions, metrics.conversions, " "metrics.cost_micros, metrics.ctr, metrics.average_cpc, metrics.conversions_value_per_cost " "FROM campaign WHERE segments.date DURING LAST_30_DAYS " "ORDER BY metrics.conversions DESC " f"LIMIT {limit}" ) def _simulate( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int ) -> List[GoogleCampaignPerformance]: simulated: List[GoogleCampaignPerformance] = [] tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) emphasis = 1 + len(set(tokens)) * 0.02 for index, scored in enumerate(campaigns[:limit]): base_clicks = max(50, int(scored.score * 10)) clicks = int(base_clicks * emphasis) impressions = max(clicks * 8, 500) conversions = round(max(1.0, scored.metrics.expected_roi * 1.5), 2) cost_micros = int(max(1_000_000, impressions * 120)) ctr = round(min(0.25, clicks / max(1, impressions)), 4) cpc = round(cost_micros / max(1, clicks) / 1_000_000, 2) roas = round(scored.metrics.expected_roi / max(0.1, cpc), 2) simulated.append( GoogleCampaignPerformance( campaign_name=f"{scored.campaign.channel.title()} - Simulated", clicks=clicks, impressions=impressions, conversions=conversions, cost_micros=cost_micros, ctr=ctr, cpc=cpc, roas=roas, source="simulated", notes=( "Simulated from marketing benchmarks; set GOOGLE_ADS_* env vars " "for live Google Ads enrichment." ), ) ) if not simulated: simulated.append( GoogleCampaignPerformance( campaign_name="Simulated Campaign", clicks=120, impressions=2400, conversions=3.0, cost_micros=2500000, ctr=0.05, cpc=0.5, roas=4.2, source="simulated", notes="Fallback simulation due to missing campaigns", ) ) return simulated class CJAffiliateCatalog: """Loads CJ affiliate offers and surfaces relevant matches.""" def __init__(self, offers: Sequence[CJAffiliateOffer]): self._offers = list(offers) @classmethod def from_file(cls, path: str = CJ_OFFERS_DATASET) -> "CJAffiliateCatalog": try: with open(path, "r", encoding="utf-8") as handle: payload = json.load(handle) except FileNotFoundError: return cls([]) except json.JSONDecodeError: return cls([]) offers: List[CJAffiliateOffer] = [] for entry in payload if isinstance(payload, list) else []: try: offer = CJAffiliateOffer( program_name=entry["program_name"], advertiser_id=str(entry["advertiser_id"]), category=entry.get("category", "Unknown"), commission_rate=float(entry.get("commission_rate", 0.0)), epc=float(entry.get("epc", 0.0)), seven_day_epc=float(entry.get("seven_day_epc", entry.get("epc", 0.0))), network_rank=int(entry.get("network_rank", 7)), payout_terms=entry.get("payout_terms", "Net30"), landing_url=entry.get("landing_url", ""), description=entry.get("description", ""), keywords=list(entry.get("keywords", [])), ) except (KeyError, TypeError, ValueError): continue offers.append(offer) return cls(offers) def match_offers( self, tokens: Sequence[str], limit: int = 3, focus: str | None = None, ) -> List[Tuple[float, CJAffiliateOffer]]: limit = max(1, limit) scored: List[Tuple[float, CJAffiliateOffer]] = [] token_set = {token.lower() for token in tokens if token} for offer in self._offers: keywords = {keyword.lower() for keyword in offer.keywords} description = offer.description.lower() category = offer.category.lower() score = offer.epc / 120.0 score += max(0.0, (6 - min(offer.network_rank, 6)) * 0.1) for token in token_set: if token in keywords: score += 1.2 elif token in description or token in category: score += 0.8 if focus and focus in category: score += 0.5 scored.append((score, offer)) scored.sort(key=lambda item: item[0], reverse=True) return scored[:limit] class CJAffiliateProcess: """Transforms CJ affiliate data into monetization playbooks.""" REQUIRED_ENV_VARS = { "CJ_DEVELOPER_KEY": "developer_key", } OPTIONAL_ENV_VARS = { "CJ_WEBSITE_ID": "website_id", "CJ_ACCOUNT_ID": "account_id", } def __init__( self, catalog: CJAffiliateCatalog | None = None, config: Dict[str, Any] | None = None, ): self._catalog = catalog or CJAffiliateCatalog.from_file() self._config = config or self._config_from_env() @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in {**cls.REQUIRED_ENV_VARS, **cls.OPTIONAL_ENV_VARS}.items(): value = os.getenv(env_var) if value: config[key] = value return config @property def configured(self) -> bool: return "developer_key" in self._config def offers( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[CJAffiliateRecommendation]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) focus = None if campaigns: focus = campaigns[0].campaign.channel.lower().split()[0] matches = self._catalog.match_offers(tokens, limit, focus) if not matches: return [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.5 avg_ctr = mean([score.metrics.expected_ctr for score in campaigns]) if campaigns else 0.03 enriched: List[CJAffiliateRecommendation] = [] for match_score, offer in matches: keyword_matches = sorted({token for token in tokens if token in {k.lower() for k in offer.keywords}}) intensity = max(0.15, min(1.8, match_score / 4.0)) projected_epc = round(offer.epc * (1 + intensity * 0.18 + avg_ctr * 4), 2) projected_revenue = round(projected_epc * max(5.0, avg_roi * 6), 2) if keyword_matches: rationale = ( f"Matches {', '.join(keyword_matches)} demand with {offer.category.lower()} payouts." ) else: rationale = f"High network rank offer aligned to {offer.category.lower()} intent." source = "cj_network" if self.configured else "cj_catalog" notes = None if not self.configured: notes = ( "Simulated from CJ offer corpus; set CJ_DEVELOPER_KEY and related env vars " "to activate live API harvesting." ) enriched.append( CJAffiliateRecommendation( program_name=offer.program_name, advertiser_id=offer.advertiser_id, category=offer.category, commission_rate=round(offer.commission_rate, 4), epc=round(offer.epc, 2), seven_day_epc=round(offer.seven_day_epc, 2), projected_epc=projected_epc, projected_monthly_revenue=projected_revenue, network_rank=offer.network_rank, payout_terms=offer.payout_terms, landing_url=offer.landing_url, rationale=rationale, source=source, notes=notes, ) ) return enriched class InfluencerCollaborationProcess: """Matches prompts with influencer partners to accelerate revenue loops.""" OPTIONAL_ENV_VARS = { "INFLUENCER_NETWORK_API_KEY": "[credential removed]", "INFLUENCER_NETWORK_WORKSPACE": "workspace", } def __init__( self, catalog: InfluencerNetworkCatalog | None = None, config: Dict[str, Any] | None = None, ) -> None: self._catalog = catalog or InfluencerNetworkCatalog() self._config = config or self._config_from_env() @classmethod def _config_from_env(cls) -> Dict[str, Any]: config: Dict[str, Any] = {} for env_var, key in cls.OPTIONAL_ENV_VARS.items(): value = os.getenv(env_var) if value: config[key] = value return config @property def configured(self) -> bool: return "api_key" in self._config def recommendations( self, prompt: str, campaigns: Sequence[CampaignScore], limit: int, ) -> List[InfluencerRecommendation]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) focus = None if campaigns: primary = campaigns[0].campaign focus = f"{primary.channel} {primary.audience}" matches = self._catalog.match_partners(tokens, focus, limit) if not matches: return [] avg_roi = mean([score.metrics.expected_roi for score in campaigns]) if campaigns else 2.2 avg_ctr = mean([score.metrics.expected_ctr for score in campaigns]) if campaigns else 0.03 avg_confidence = ( mean([score.metrics.confidence for score in campaigns]) if campaigns else 0.55 ) reach_multiplier = max(1.1, 1 + (avg_confidence - 0.5)) recs: List[InfluencerRecommendation] = [] for index, (match_score, partner) in enumerate(matches): collab_formats = partner.collab_formats or ["sponsored integration"] collab_format = collab_formats[index % len(collab_formats)] estimated_reach = int( round(partner.audience_size * partner.engagement_rate * reach_multiplier) ) estimated_reach = max(estimated_reach, int(partner.audience_size * 0.02)) lead_rate = max(0.015, avg_ctr * 1.15 + partner.engagement_rate / 3) projected_leads = max(12, int(round(estimated_reach * lead_rate))) investment = partner.avg_cpm * estimated_reach / 1000.0 revenue_per_lead = max(95.0, avg_roi * 120.0) projected_revenue = round(projected_leads * revenue_per_lead, 2) projected_roi = ( round(projected_revenue / investment, 2) if investment else round(avg_roi * 3, 2) ) keyword_matches = sorted( { token for token in tokens if token in {keyword.lower() for keyword in partner.keywords} } ) if keyword_matches: rationale = ( "Maps " + "/".join(keyword_matches[:3]) + f" intent into {partner.platform} {collab_format} with {partner.niche.lower()} authority." ) else: rationale = ( f"Pairs {partner.niche.lower()} reach with {partner.conversion_focus.lower()} focus " "to amplify campaign demand." ) if partner.case_study: rationale += f" Proof: {partner.case_study}" source = "influencer_api" if self.configured else "influencer_catalog" notes = None if not self.configured: notes = ( "Simulated from influencer partner corpus; set INFLUENCER_NETWORK_API_KEY to " "activate live network sourcing." ) recs.append( InfluencerRecommendation( name=partner.name, platform=partner.platform, niche=partner.niche, collab_format=collab_format, audience_size=partner.audience_size, engagement_rate=round(partner.engagement_rate, 4), estimated_reach=estimated_reach, projected_cpm=round(partner.avg_cpm, 2), projected_leads=projected_leads, projected_revenue=projected_revenue, projected_roi=projected_roi, rationale=rationale, source=source, notes=notes, ) ) return recs class AutomationSprintPlanner: """Builds a three-hour automation sprint tailored to the prompt context.""" def __init__( self, templates: Dict[str, Any] | None = None, defaults: Dict[str, Any] | None = None, ): data = templates or self._load_templates() self._templates = data.get("stages", {}) self._overlays = data.get("focus_overlays", {}) base_defaults = data.get("defaults", {}).copy() if defaults: base_defaults.update(defaults) self._defaults = base_defaults @staticmethod def _load_templates(path: str = AUTOMATION_SPRINTS_DATASET) -> Dict[str, Any]: with open(path, "r", encoding="utf-8") as handle: return json.load(handle) def _stage_templates(self, stage: str) -> List[Dict[str, Any]]: if stage in self._templates: return list(self._templates[stage]) if "conversion" in self._templates: return list(self._templates["conversion"]) for entries in self._templates.values(): if entries: return list(entries) return [] def _focus_overlays(self, focus: str) -> List[Dict[str, Any]]: lowered = focus.lower() for key, tasks in self._overlays.items(): if key in lowered: return list(tasks) return [] @staticmethod def _safe_format(template: str, context: Dict[str, str]) -> str: class _SafeDict(dict): def __missing__(self, key: str) -> str: # pragma: no cover - defensive fallback return "{" + key + "}" return template.format_map(_SafeDict(context)) @staticmethod def _campaign_context( campaigns: Sequence[CampaignScore], index: int ) -> Dict[str, str]: if campaigns: primary = campaigns[0].campaign reference = campaigns[index % len(campaigns)].campaign secondary = campaigns[1 % len(campaigns)].campaign if len(campaigns) > 1 else primary return { "channel": reference.channel, "offer": reference.offer, "audience": reference.audience, "objective": reference.objective, "primary_channel": primary.channel, "primary_offer": primary.offer, "primary_audience": primary.audience, "primary_objective": primary.objective, "support_channel": secondary.channel, "support_offer": secondary.offer, } return { "channel": "omnichannel automation", "offer": "flagship offer", "audience": "core buyers", "objective": "pipeline velocity", "primary_channel": "omnichannel", "primary_offer": "flagship offer", "primary_audience": "core buyers", "primary_objective": "pipeline velocity", "support_channel": "email", "support_offer": "activation play", } def plan( self, prompt: str, diagnostics: PromptDiagnostics, campaigns: Sequence[CampaignScore], limit: int, ) -> AutomationSprint: block = int(self._defaults.get("block_minutes", 30)) total_minutes = int(self._defaults.get("total_minutes", 180)) blocks = max(1, total_minutes // max(1, block)) templates = self._stage_templates(diagnostics.stage) overlays = self._focus_overlays(diagnostics.focus) if overlays: templates.extend(overlays) if not templates: templates = [ { "activity": "Audit acquisition funnel touchpoints", "outcome": "Document automation opportunities", "tooling": ["Notion"], "kpis": ["pipeline velocity"], "automation_level": "assist", } ] tasks: List[AutomationTask] = [] summary_drivers: List[str] = [] for idx in range(blocks): template = templates[idx % len(templates)] context = self._campaign_context(campaigns, idx) context["stage"] = diagnostics.stage context["focus"] = diagnostics.focus activity = self._safe_format(template.get("activity", "Execute automation sprint"), context) outcome = self._safe_format(template.get("outcome", "Drive measurable impact"), context) tooling = list(template.get("tooling", [])) kpis = [kpi.lower() for kpi in template.get("kpis", [])] automation_level = template.get("automation_level", "assist") start_minute = idx * block end_minute = start_minute + block source = self._defaults.get("source", "automation_playbooks") tasks.append( AutomationTask( start_minute=start_minute, end_minute=end_minute, activity=activity, outcome=outcome, tooling=tooling, kpis=kpis, automation_level=automation_level, source=source, ) ) channel = context.get("channel") if channel and channel not in summary_drivers: summary_drivers.append(channel) channels_summary = ", ".join(summary_drivers[:3]) or "omnichannel" summary = ( f"Three-hour automation sprint targeting {diagnostics.stage} intent for {diagnostics.focus} focus " f"anchored in {channels_summary} plays." ) notes = self._defaults.get("notes") return AutomationSprint( total_minutes=blocks * block, stage=diagnostics.stage, focus=diagnostics.focus, summary=summary, tasks=tasks, notes=notes, source=self._defaults.get("source", "automation_playbooks"), ) class MarketingIntelligenceEngine: """Ranks marketing campaigns against free-form prompts.""" def __init__( self, campaigns: Sequence[MarketingCampaign], benchmarks: MarketingBenchmarks | None = None, google_process: GoogleAdsProcess | None = None, cj_process: CJAffiliateProcess | None = None, crypto_process: CryptoMarketProcess | None = None, stripe_process: StripeProcess | None = None, paypal_process: PayPalProcess | None = None, amazon_process: AmazonMarketplaceProcess | None = None, ebay_process: EbayMarketplaceProcess | None = None, aws_process: AWSRevenueProcess | None = None, budget_process: BudgetAllocatorProcess | None = None, automation_process: AutomationSprintPlanner | None = None, learning_process: LearningLoopProcess | None = None, competitive_process: CompetitiveIntelligenceProcess | None = None, influencer_process: InfluencerCollaborationProcess | None = None, scenario_process: "ScenarioPlanningProcess" | None = None, amazon_process: AmazonMarketplaceProcess | None = None, aws_process: AWSRevenueProcess | None = None, ): if not campaigns: raise ValueError("MarketingIntelligenceEngine requires at least one campaign") self._campaigns = list(campaigns) self._benchmarks = benchmarks or MarketingBenchmarks.from_file() self._google_process = google_process or GoogleAdsProcess() self._cj_process = cj_process or CJAffiliateProcess() self._crypto_process = crypto_process or CryptoMarketProcess() self._stripe_process = stripe_process or StripeProcess() self._paypal_process = paypal_process or PayPalProcess() self._amazon_process = amazon_process or AmazonMarketplaceProcess() self._ebay_process = ebay_process or EbayMarketplaceProcess() self._aws_process = aws_process or AWSRevenueProcess() self._budget_process = budget_process or BudgetAllocatorProcess() self._automation_process = automation_process or AutomationSprintPlanner() self._learning_process = learning_process or LearningLoopProcess() self._competitive_process = competitive_process or CompetitiveIntelligenceProcess() self._influencer_process = influencer_process or InfluencerCollaborationProcess() self._scenario_process = scenario_process or ScenarioPlanningProcess() self._amazon_process = amazon_process or AmazonMarketplaceProcess() self._aws_process = aws_process or AWSRevenueProcess() @classmethod def from_file( cls, path: str = MARKETING_ENUMERATION, benchmark_path: str = MARKETING_BENCHMARKS, ) -> "MarketingIntelligenceEngine": lines = _load_lines(path) campaigns = [MarketingCampaign.parse(line) for line in lines] benchmarks = MarketingBenchmarks.from_file(benchmark_path) return cls(campaigns, benchmarks) @staticmethod def _keyword_set(prompt: str) -> List[str]: tokens = re.findall(r"[a-zA-Z0-9]+", prompt.lower()) filtered = [token for token in tokens if len(token) > 2] return filtered or ["campaign"] def recommend(self, prompt: str, limit: int = 3) -> List[MarketingCampaign]: tokens = self._keyword_set(prompt) def score(campaign: MarketingCampaign) -> tuple[int, int, str]: haystacks = { "channel": campaign.channel.lower(), "audience": campaign.audience.lower(), "offer": campaign.offer.lower(), "objective": campaign.objective.lower(), } weighted = 0 matched_features: set[str] = set() for token in tokens: for feature, text in haystacks.items(): if token in text: matched_features.add(feature) weight = 4 if feature == "audience" else 3 if feature == "offer" else 2 weighted += weight # fallback to slight preference for broader coverage even if nothing matched coverage_bonus = len(matched_features) return (-(weighted + coverage_bonus), len(campaign.raw), campaign.raw) ranked = sorted(self._campaigns, key=score) return ranked[: max(1, limit)] def recommend_statistical(self, prompt: str, limit: int = 3) -> List[CampaignScore]: tokens = self._keyword_set(prompt) scored: List[CampaignScore] = [] for campaign in self._campaigns: metrics = self._benchmarks.metrics_for(campaign) keyword_hits: Dict[str, int] = {"channel": 0, "audience": 0, "offer": 0, "objective": 0} haystacks = { "channel": campaign.channel.lower(), "audience": campaign.audience.lower(), "offer": campaign.offer.lower(), "objective": campaign.objective.lower(), } match_bonus = 0.0 for token in tokens: for feature, text in haystacks.items(): if token in text: keyword_hits[feature] += 1 match_bonus += 0.35 roi_component = metrics.expected_roi * 0.6 ctr_component = metrics.expected_ctr * 80.0 * 0.25 confidence_component = metrics.confidence * 10.0 * 0.1 keyword_component = match_bonus composite = roi_component + ctr_component + confidence_component + keyword_component scored.append( CampaignScore( campaign=campaign, score=composite, metrics=metrics, keyword_coverage=keyword_hits, ) ) ranked = sorted(scored, key=lambda entry: entry.score, reverse=True) return ranked[: max(1, limit)] def summarize(self, prompt: str, campaigns: Sequence[MarketingCampaign]) -> str: tokens = self._keyword_set(prompt) highlights = ", ".join(sorted(set(tokens))) count = len(campaigns) return f"Surface {count} campaign plays tuned for {highlights}." @staticmethod def _infer_stage(tokens: Sequence[str]) -> Tuple[str, List[str]]: mapping = { "awareness": {"awareness", "reach", "impressions", "brand", "launch", "attention"}, "consideration": {"consideration", "education", "webinar", "nurture", "pipeline", "engagement"}, "conversion": { "conversion", "roi", "ctr", "leads", "demos", "trial", "customers", "acquisition", }, "retention": {"retention", "renewal", "expansion", "upsell", "loyalty", "churn"}, } hits: Dict[str, List[str]] = {key: [] for key in mapping} for token in tokens: for stage, keywords in mapping.items(): if token in keywords: hits[stage].append(token) stage = max(mapping, key=lambda key: len(hits[key])) if all(len(values) == 0 for values in hits.values()): stage = "conversion" return stage, hits[stage] @staticmethod def _infer_urgency(prompt: str) -> str: lowered = prompt.lower() if any(keyword in lowered for keyword in ["urgent", "asap", "immediately", "right away", "now"]): return "urgent" if any(keyword in lowered for keyword in ["this quarter", "q4", "deadline", "accelerate"]): return "time-sensitive" return "standard" @staticmethod def _infer_focus(tokens: Sequence[str]) -> Tuple[str, List[str]]: focus_buckets = { "enterprise b2b": {"enterprise", "cxo", "c-suite", "fortune", "b2b", "saas"}, "startup founders": {"founder", "startup", "scaleup", "seed", "series"}, "consumer": {"consumer", "b2c", "retail", "shopper", "app"}, "developer": {"developer", "devops", "engineer", "technical", "api"}, } hits: Dict[str, List[str]] = {bucket: [] for bucket in focus_buckets} for token in tokens: for focus, keywords in focus_buckets.items(): if token in keywords: hits[focus].append(token) focus = max(focus_buckets, key=lambda key: len(hits[key])) if len(hits[focus]) == 0: return "broad b2b", [] return focus, hits[focus] @staticmethod def _recommend_kpis(stage: str) -> List[str]: mapping = { "awareness": ["impressions", "share of voice", "reach growth"], "consideration": ["content engagement", "marketing qualified leads", "pipeline velocity"], "conversion": ["sales qualified leads", "demo-to-close rate", "customer acquisition cost"], "retention": ["net revenue retention", "renewal rate", "expansion ARR"], } return mapping.get(stage, ["pipeline velocity", "conversion rate"]) @staticmethod def _recommend_opportunities(stage: str, focus: str) -> List[str]: opportunities = { "awareness": [ "Anchor thought-leadership content to prime the market", "Deploy programmatic amplification across hero stories", ], "consideration": [ "Introduce nurture sequences aligned to buyer pains", "Layer intent scoring to prioritize engaged accounts", ], "conversion": [ "Bundle conversion offers with social proof assets", "Tighten sales enablement loops with marketing triggers", ], "retention": [ "Launch customer marketing to reinforce product value", "Pair success cadences with expansion playbooks", ], } base = opportunities.get(stage, []) if focus.startswith("enterprise"): base = base + ["Align executive-level narratives with ROI benchmarks"] elif "startup" in focus: base = base + ["Stand up scrappy experiments to validate fast wins"] elif "consumer" in focus: base = base + ["Personalize lifecycle messaging using behavioral cohorts"] return base @staticmethod def _detect_risks(prompt: str) -> List[str]: lowered = prompt.lower() risks: List[str] = [] if "flat" in lowered or "stalled" in lowered or "plateau" in lowered: risks.append("Performance plateau signaled") if "limited budget" in lowered or "tight budget" in lowered: risks.append("Budget constraints highlighted") if "new market" in lowered or "unknown" in lowered: risks.append("Market unfamiliarity risk") if "churn" in lowered or "retention" in lowered: risks.append("Retention fragility noted") return risks def diagnose(self, prompt: str) -> PromptDiagnostics: tokens = self._keyword_set(prompt) stage, stage_hits = self._infer_stage(tokens) urgency = self._infer_urgency(prompt) focus, focus_hits = self._infer_focus(tokens) kpis = self._recommend_kpis(stage) opportunities = self._recommend_opportunities(stage, focus) risks = self._detect_risks(prompt) keyword_summary = { "intent": stage_hits, "focus": focus_hits, "tokens": tokens, } confidence_seed = len(stage_hits) + len(focus_hits) confidence = max(0.35, min(0.95, 0.35 + 0.1 * confidence_seed)) return PromptDiagnostics( stage=stage, urgency=urgency, focus=focus, recommended_kpis=kpis, opportunities=opportunities, risk_signals=risks, keyword_summary=keyword_summary, confidence=round(confidence, 2), ) def portfolio(self, prompt: str, campaigns: Sequence[CampaignScore]) -> CampaignMetrics: if not campaigns: raise ValueError("portfolio requires at least one campaign score") roi = sum(entry.metrics.expected_roi for entry in campaigns) / len(campaigns) ctr = sum(entry.metrics.expected_ctr for entry in campaigns) / len(campaigns) confidence = sum(entry.metrics.confidence for entry in campaigns) / len(campaigns) drivers: Dict[str, float] = {} for entry in campaigns: for feature, value in entry.metrics.drivers.items(): drivers[feature] = max(drivers.get(feature, 0.0), value) return CampaignMetrics( expected_roi=roi, expected_ctr=ctr, confidence=confidence, drivers=drivers, ) def keywords(self, prompt: str) -> List[str]: return self._keyword_set(prompt) def expansion_grid(self, prompt: str, campaigns: Sequence[CampaignScore]) -> List[GrowthExperiment]: """Design a set of Experiment Growth Grid (EGG) plays from campaign rankings.""" if not campaigns: raise ValueError("expansion_grid requires at least one campaign score") diagnostics = self.diagnose(prompt) stage_recipes: Dict[str, List[Dict[str, str]]] = { "awareness": [ { "name": "Narrative Amplification Sprint", "hypothesis": ( "If we spotlight {offer} through {channel}, " "we will warm {audience} toward {objective}." ), "play": "Launch hero content and amplify across paid/owned reach streams.", "metric": "impressions", }, { "name": "Thought Leadership Cascade", "hypothesis": ( "Positioning {audience} challenges alongside {offer} " "via {channel} will expand top-of-funnel attention." ), "play": "Sequence authoritative narratives across social and partner syndication.", "metric": "share of voice", }, ], "consideration": [ { "name": "Intent Magnet Program", "hypothesis": ( "If we orchestrate {offer} journeys through {channel}, " "we can mature {audience} into evaluators for {objective}." ), "play": "Build nurture modules triggered by behavioral intent signals.", "metric": "marketing qualified leads", }, { "name": "Education Sprint", "hypothesis": ( "Providing {audience} with {offer} across {channel} " "will compress evaluation cycles." ), "play": "Layer webinars, playbooks, and retargeting to reinforce learnings.", "metric": "content engagement", }, ], "conversion": [ { "name": "Pipeline Acceleration Lab", "hypothesis": ( "If {audience} experience {offer} via {channel}, " "we can unlock {objective} faster." ), "play": "Run multi-touch conversion blitz with calibrated social proof.", "metric": "sales qualified leads", }, { "name": "Revenue Experiment Track", "hypothesis": ( "Blending {offer} within {channel} for {audience} will uplift deal velocity." ), "play": "Pair high-intent triggers with offer experimentation and CRO support.", "metric": "conversion rate", }, ], "retention": [ { "name": "Value Expansion Studio", "hypothesis": ( "If {audience} engage with {offer} programs via {channel}, " "we will fortify {objective}." ), "play": "Launch customer storytelling and advocacy loops to reinforce value.", "metric": "renewal rate", }, { "name": "Lifecycle Momentum Cell", "hypothesis": ( "Activating {offer} through {channel} for {audience} " "will catalyze expansion outcomes." ), "play": "Coordinate success-led campaigns with product usage nudges.", "metric": "net revenue retention", }, ], } focus_overlays: Dict[str, Dict[str, str]] = { "enterprise b2b": { "play": "Map executive-specific proof points and ABM orchestration layers.", "metric": "executive meeting volume", }, "startup founders": { "play": "Prototype scrappy experiments with rapid iteration cadences.", "metric": "activation-to-demo ratio", }, "consumer": { "play": "Employ personalization matrices and lifecycle messaging bursts.", "metric": "repeat purchase rate", }, "developer": { "play": "Enable technical champions with sandboxes, tutorials, and community proof.", "metric": "trial-to-adoption rate", }, "default": { "play": "Instrument experiment tracking with weekly conversion retros.", "metric": "conversion rate", }, } base_recipes = stage_recipes.get(diagnostics.stage, stage_recipes["conversion"]) overlay = focus_overlays.get(diagnostics.focus, focus_overlays["default"]) recommended = diagnostics.recommended_kpis or ["conversion rate"] experiments: List[GrowthExperiment] = [] for index, scored in enumerate(campaigns[: max(1, len(campaigns))]): recipe = base_recipes[index % len(base_recipes)] name = f"{recipe['name']} via {scored.campaign.channel.title()}" hypothesis = recipe["hypothesis"].format( offer=scored.campaign.offer, channel=scored.campaign.channel, audience=scored.campaign.audience, objective=scored.campaign.objective, ) playbook = [ f"Activate {scored.campaign.channel} targeting {scored.campaign.audience}.", recipe["play"], overlay["play"], f"Align offer '{scored.campaign.offer}' to accelerate {scored.campaign.objective} outcomes.", ] primary_metric = recipe.get("metric", recommended[0]) secondary_candidates = set(recommended[1:]) secondary_candidates.add(overlay["metric"]) secondary_metrics = sorted(secondary_candidates) confidence = (diagnostics.confidence + scored.metrics.confidence) / 2 experiments.append( GrowthExperiment( name=name, hypothesis=hypothesis, primary_metric=primary_metric, secondary_metrics=secondary_metrics, playbook=playbook, confidence=round(max(0.2, min(0.99, confidence)), 2), ) ) return experiments def google_ads_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[GoogleCampaignPerformance]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._google_process.performance(prompt, scored, limit) def cj_affiliate_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[CJAffiliateRecommendation]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._cj_process.offers(prompt, scored, limit) def crypto_market_enrichment( self, prompt: str, limit: int = 3, ) -> List[CryptoMarketSnapshot]: return self._crypto_process.market_data(prompt, limit) def stripe_checkout_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[StripeMonetizationPlan]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._stripe_process.plans(prompt, scored, limit) def paypal_checkout_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[PayPalMonetizationPlan]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._paypal_process.plans(prompt, scored, limit) def influencer_collaboration_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[InfluencerRecommendation]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._influencer_process.recommendations(prompt, scored, limit) def amazon_marketplace_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[AmazonProductRecommendation]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._amazon_process.listings(prompt, scored, limit) def ebay_marketplace_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[EbayRevenuePlay]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._ebay_process.listings(prompt, scored, limit) def aws_cloud_enrichment( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[AWSRevenueRecommendation]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return [] return self._aws_process.plays(prompt, scored, limit) def budget_optimizer( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> BudgetPlan: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) if not scored: return BudgetPlan( total_budget=0.0, allocations=[], expected_revenue=0.0, expected_roi=0.0, payback_period_weeks=0.0, summary="No campaigns available for budget allocation.", ) return self._budget_process.plan(prompt, scored, limit) def automation_sprint( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> AutomationSprint: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) diagnostics = self.diagnose(prompt) return self._automation_process.plan(prompt, diagnostics, scored, limit) def competitive_landscape( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[CompetitiveSignal]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) diagnostics = self.diagnose(prompt) return self._competitive_process.signals(prompt, diagnostics, scored, limit) def learning_loop( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, limit: int = 3, ) -> List[LearningLoopRecommendation]: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) diagnostics = self.diagnose(prompt) return self._learning_process.recommend(prompt, diagnostics, scored, limit) def scenario_planning( self, prompt: str, campaigns: Sequence[CampaignScore] | None = None, *, limit: int = 3, budget: BudgetPlan | None = None, google_ads: Sequence[GoogleCampaignPerformance] | None = None, cj_affiliate: Sequence[CJAffiliateRecommendation] | None = None, amazon: Sequence[AmazonProductRecommendation] | None = None, ebay: Sequence[EbayRevenuePlay] | None = None, aws: Sequence[AWSRevenueRecommendation] | None = None, stripe: Sequence[StripeMonetizationPlan] | None = None, paypal: Sequence[PayPalMonetizationPlan] | None = None, crypto: Sequence[CryptoMarketSnapshot] | None = None, influencers: Sequence[InfluencerRecommendation] | None = None, ) -> ScenarioAnalysis: scored = list(campaigns) if campaigns is not None else self.recommend_statistical(prompt, limit) diagnostics = self.diagnose(prompt) return self._scenario_process.analyze( prompt, diagnostics, scored, budget=budget, google_ads=google_ads or [], cj_affiliate=cj_affiliate or [], amazon=amazon or [], ebay=ebay or [], aws=aws or [], stripe=stripe or [], paypal=paypal or [], crypto=crypto or [], influencers=influencers or [], limit=limit, ) def excellence_summary( self, prompt: str, campaigns: Sequence[CampaignScore], *, limit: int, rag: Sequence[MarketingCampaign], egg: Sequence[GrowthExperiment], google_ads: Sequence[GoogleCampaignPerformance], cj_affiliate: Sequence[CJAffiliateRecommendation], crypto_markets: Sequence[CryptoMarketSnapshot], stripe: Sequence[StripeMonetizationPlan], paypal: Sequence[PayPalMonetizationPlan], amazon: Sequence[AmazonProductRecommendation], ebay: Sequence[EbayRevenuePlay], aws: Sequence[AWSRevenueRecommendation], budget: BudgetPlan | None, automation: AutomationSprint | None, learning_loop: Sequence[LearningLoopRecommendation], competitive: Sequence[CompetitiveSignal], influencers: Sequence[InfluencerRecommendation], ) -> ExcellenceSummary: limit = max(1, limit) roi_avg = mean(entry.metrics.expected_roi for entry in campaigns) if campaigns else 0.0 ctr_avg = mean(entry.metrics.expected_ctr for entry in campaigns) if campaigns else 0.0 confidence_avg = ( mean(entry.metrics.confidence for entry in campaigns) if campaigns else 0.0 ) roi_norm = min(1.0, max(0.0, roi_avg / 5.0)) ctr_norm = min(1.0, max(0.0, ctr_avg / 0.05)) confidence_norm = min(1.0, max(0.0, confidence_avg)) coverage_map: Dict[str, float] = { "rag": min(1.0, len(rag) / limit), "egg": min(1.0, len(egg) / limit), "google_ads": min(1.0, len(google_ads) / limit), "cj_affiliate": min(1.0, len(cj_affiliate) / limit), "crypto_markets": min(1.0, len(crypto_markets) / limit), "stripe": min(1.0, len(stripe) / limit), "paypal": min(1.0, len(paypal) / limit), "influencer_collaborations": min(1.0, len(influencers) / limit), "amazon_marketplace": min(1.0, len(amazon) / limit), "ebay_marketplace": min(1.0, len(ebay) / limit), "aws_cloud": min(1.0, len(aws) / limit), "learning_loop": min(1.0, len(learning_loop) / limit), "competitive_landscape": min(1.0, len(competitive) / limit), } coverage_map["budget_optimizer"] = 1.0 if budget and budget.allocations else 0.0 coverage_map["automation"] = 1.0 if automation and automation.tasks else 0.0 coverage_norm = mean(coverage_map.values()) if coverage_map else 0.0 excellence_index = round( (roi_norm * 0.35 + ctr_norm * 0.2 + confidence_norm * 0.25 + coverage_norm * 0.2) * 100, 2, ) if excellence_index >= 85: maturity = "world-class" elif excellence_index >= 70: maturity = "elite" elif excellence_index >= 55: maturity = "scaling" else: maturity = "emerging" keywords = self.keywords(prompt)[:3] if keywords: headline_focus = ", ".join(keywords) else: headline_focus = "core growth themes" headline = ( f"{maturity.title()} marketing ANI readiness anchored in {headline_focus}." ) strengths: List[str] = [] if roi_norm >= 0.75: strengths.append("Benchmark ROI trajectory rivals top performers.") elif roi_norm >= 0.5: strengths.append("ROI projections support confident scaling.") if coverage_norm >= 0.7: strengths.append("Process coverage spans key enrichment workflows.") if len(competitive) >= 1: strengths.append("Competitive counter-moves actively inform campaign plans.") if len(influencers) >= 1: strengths.append("Influencer collaborations unlock rapid audience amplification.") watchouts: List[str] = [] if ctr_norm < 0.4: watchouts.append( "Click-through benchmarks trail aggressive targets; iterate creative experiments." ) if confidence_norm < 0.6: watchouts.append("Benchmark confidence is moderate; collect more lift validation.") if coverage_norm < 0.5: watchouts.append( "Several enrichment processes returned limited data; review integration readiness." ) if len(influencers) == 0: watchouts.append("Source influencer partners to extend reach beyond owned channels.") if not strengths: strengths.append("Foundational datasets available for orchestration.") if not watchouts: watchouts.append("Continue monitoring live integrations to maintain excellence.") notes = ( "Excellence index synthesizes ROI, CTR, confidence, and process coverage heuristics." ) return ExcellenceSummary( excellence_index=excellence_index, maturity_level=maturity, headline=headline, strengths=strengths, watchouts=watchouts, process_coverage=coverage_map, notes=notes, ) def executive_playbook( self, prompt: str, campaigns: Sequence[CampaignScore], *, limit: int, rag: Sequence[MarketingCampaign], egg: Sequence[GrowthExperiment], google_ads: Sequence[GoogleCampaignPerformance], cj_affiliate: Sequence[CJAffiliateRecommendation], amazon: Sequence[AmazonProductRecommendation], ebay: Sequence[EbayRevenuePlay], paypal: Sequence[PayPalMonetizationPlan], budget: BudgetPlan | None, automation: AutomationSprint | None, learning_loop: Sequence[LearningLoopRecommendation], competitive: Sequence[CompetitiveSignal], influencers: Sequence[InfluencerRecommendation], excellence: ExcellenceSummary | None = None, ) -> ExecutivePlaybook: diagnostics = self.diagnose(prompt) def _channel_key(text: str) -> str: return re.sub(r"\s+", " ", text.lower().strip()) limit = max(1, limit) top_scores = list(campaigns[: limit if campaigns else 1]) if not top_scores and campaigns: top_scores = list(campaigns) experiment_map: Dict[str, GrowthExperiment] = {} for experiment in egg: name_lower = experiment.name.lower() channel_fragment: str | None = None if " via " in name_lower: channel_fragment = name_lower.split(" via ", 1)[1].strip() if (not channel_fragment or not channel_fragment.strip()) and experiment.playbook: first_step = experiment.playbook[0].lower() match = re.search(r"activate (.+?) targeting", first_step) if match: channel_fragment = match.group(1).strip() if channel_fragment: experiment_map.setdefault(_channel_key(channel_fragment), experiment) budget_map: Dict[str, BudgetAllocation] = {} if budget: for allocation in budget.allocations: budget_map[_channel_key(allocation.channel)] = allocation learning_map: Dict[str, List[LearningLoopRecommendation]] = {} for recommendation in learning_loop: channel_hint = recommendation.channel or recommendation.stage or recommendation.play_name key = _channel_key(channel_hint) learning_map.setdefault(key, []).append(recommendation) competitive_map: Dict[str, List[CompetitiveSignal]] = {} for signal in competitive: competitive_map.setdefault(_channel_key(signal.channel), []).append(signal) rag_channels = {idx: rag_campaign.channel for idx, rag_campaign in enumerate(rag)} influencer_pool = list(influencers) urgency_to_horizon = {"urgent": 72, "time-sensitive": 120, "standard": 168} base_horizon = urgency_to_horizon.get(diagnostics.urgency, 168) campaign_confidence = ( mean(score.metrics.confidence for score in top_scores) if top_scores else 0.5 ) roi_confidence = ( mean(score.metrics.expected_roi for score in top_scores) if top_scores else 0.5 ) budget_confidence = ( min(0.95, max(0.35, (budget.expected_roi / 5.0))) if budget else 0.55 ) learning_confidence = ( mean(rec.confidence for rec in learning_loop) if learning_loop else 0.55 ) automation_confidence = 0.75 if automation and automation.tasks else 0.5 overall_confidence = round( min( 0.99, max( 0.35, mean( [ diagnostics.confidence, campaign_confidence, min(0.95, max(0.3, roi_confidence / 5.0)), budget_confidence, learning_confidence, automation_confidence, ] ), ), ), 2, ) directives: List[StrategicDirective] = [] north_star_metric = ( diagnostics.recommended_kpis[0] if diagnostics.recommended_kpis else "revenue acceleration" ) for index, score in enumerate(top_scores): channel = score.campaign.channel channel_key = _channel_key(channel) allocation = budget_map.get(channel_key) experiment = experiment_map.get(channel_key) learnings = learning_map.get(channel_key, []) competitors = competitive_map.get(channel_key, []) google_signal = google_ads[index % len(google_ads)] if google_ads else None affiliate_signal = cj_affiliate[index % len(cj_affiliate)] if cj_affiliate else None amazon_signal = amazon[index % len(amazon)] if amazon else None ebay_signal = ebay[index % len(ebay)] if ebay else None paypal_signal = paypal[index % len(paypal)] if paypal else None influencer_signal = ( influencer_pool[index % len(influencer_pool)] if influencer_pool else None ) supporting_channels = [channel] if google_signal: supporting_channels.append("Google Ads") if affiliate_signal: supporting_channels.append("Affiliate") if amazon_signal: supporting_channels.append("Marketplace") if ebay_signal: supporting_channels.append("eBay") if paypal_signal: supporting_channels.append("PayPal") if influencer_signal: supporting_channels.append(f"Influencer - {influencer_signal.platform}") if automation and automation.tasks: supporting_channels.append("Automation Sprint") supporting_channels = list(dict.fromkeys(supporting_channels)) action_steps: List[str] = [ ( f"Activate {channel} program targeting {score.campaign.audience} to " f"{score.campaign.objective}." ) ] if experiment: action_steps.append( f"Run Experiment '{experiment.name}' optimizing {experiment.primary_metric}." ) if google_signal: action_steps.append( f"Model spend with Google Ads ROAS {google_signal.roas:.1f}x benchmark." ) if affiliate_signal: commission_pct = affiliate_signal.commission_rate * 100 action_steps.append( f"Layer CJ affiliate offer '{affiliate_signal.program_name}' at {commission_pct:.1f}% commission." ) if amazon_signal: action_steps.append( f"Promote marketplace listing '{amazon_signal.title}' to unlock partner revenue." ) if ebay_signal: action_steps.append( ( f"Launch eBay offer '{ebay_signal.title}' leveraging {ebay_signal.affiliate_rate * 100:.1f}%" " partner share and rapid sell-through." ) ) if paypal_signal: action_steps.append( ( f"Enable PayPal {paypal_signal.checkout_flow} flow with {paypal_signal.payout_schedule} " "payout cadence for dependable paychecks." ) ) if influencer_signal: action_steps.append( ( f"Activate {influencer_signal.collab_format} with {influencer_signal.name} " f"to reach {influencer_signal.estimated_reach:,.0f} engaged prospects." ) ) if automation and automation.tasks: first_task = automation.tasks[0] kpi_focus = first_task.kpis[0] if first_task.kpis else "primary KPI" action_steps.append( f"Kick off automation sprint task '{first_task.activity}' for {kpi_focus}." ) if learnings: next_action = ( learnings[0].next_actions[0] if learnings[0].next_actions else "capture fresh experiment data" ) action_steps.append( f"Apply learning '{learnings[0].learning}' with next action '{next_action}'." ) action_steps = list(dict.fromkeys(action_steps)) dependencies: List[str] = [] if allocation: dependencies.append( f"Allocate ${allocation.allocation_usd:,.0f} to {channel} with expected ${allocation.expected_revenue:,.0f} returns" ) else: dependencies.append("Confirm working budget envelope for channel execution") if google_signal and google_signal.source != "simulated": dependencies.append("Validate Google Ads account credentials and conversion tracking") if affiliate_signal and affiliate_signal.source != "cj_catalog": dependencies.append("Sync CJ affiliate program approvals") if automation and automation.tasks: dependencies.append("Reserve automation operators for 3-hour sprint") if ebay_signal and ebay_signal.source != "ebay_catalog": dependencies.append("Confirm eBay developer token and partner campaign tracking") if paypal_signal and paypal_signal.source != "simulated": dependencies.append("Verify PayPal payout configuration and webhook capture") elif paypal_signal: dependencies.append("Export PAYPAL credentials to activate live paychecks") if influencer_signal: est_investment = influencer_signal.projected_cpm * influencer_signal.estimated_reach / 1000.0 dependencies.append( ( f"Fund influencer collaboration (~${est_investment:,.0f}) to secure " f"{influencer_signal.projected_roi:.1f}x projected ROI" ) ) risk_mitigations: List[str] = [] for risk in diagnostics.risk_signals[:2]: risk_mitigations.append(f"Mitigate risk: {risk}") for competitor in competitors[:1]: risk_mitigations.append( f"Counter {competitor.competitor} via {competitor.recommended_play}" ) if learnings and learnings[0].losses: risk_mitigations.append( f"Avoid prior loss: {learnings[0].losses[0]}" ) if influencer_signal and influencer_signal.projected_roi < 3.5: risk_mitigations.append( "Negotiate performance clauses with influencer partner to protect ROI" ) if not risk_mitigations: risk_mitigations.append("Maintain rapid feedback loops across processes") directive_confidence = round( min( 0.99, max( 0.3, mean( [ score.metrics.confidence, min(0.95, max(0.3, score.metrics.expected_roi / 5.0)), learnings[0].confidence if learnings else diagnostics.confidence, ] ), ), ), 2, ) time_horizon = base_horizon + index * 48 supporting_metrics_set: set[str] = {north_star_metric} if experiment: supporting_metrics_set.add(experiment.primary_metric) supporting_metrics_set.update(experiment.secondary_metrics) if influencer_signal: supporting_metrics_set.add("influencer reach") directive = StrategicDirective( name=f"Directive {index + 1}: {score.campaign.channel.title()} Surge", priority=index + 1, objective=score.campaign.objective, primary_channel=channel, supporting_channels=supporting_channels, investment_usd=round(allocation.allocation_usd, 2) if allocation else None, expected_revenue_usd=round(allocation.expected_revenue, 2) if allocation else None, confidence=directive_confidence, time_horizon_hours=time_horizon, north_star_metric=north_star_metric, supporting_metrics=sorted(supporting_metrics_set), action_steps=action_steps, dependencies=dependencies, risk_mitigations=risk_mitigations, inspiration=" | ".join( filter( None, [ experiment.name if experiment else None, learnings[0].play_name if learnings else None, competitors[0].competitor if competitors else None, rag_channels.get(index), ], ) ) or "Campaign intelligence fusion", ) directives.append(directive) summary = ( f"Synthesize {len(directives)} directives to accelerate {diagnostics.stage} outcomes " f"for {diagnostics.focus}." ) notes_candidates = [] if excellence: notes_candidates.append(excellence.headline) if budget: notes_candidates.append(budget.summary) if automation: notes_candidates.append(automation.summary) if influencer_pool: notes_candidates.append( ( f"Influencer plan anchored by {influencer_pool[0].name} " f"({influencer_pool[0].projected_roi:.1f}x ROI outlook)" ) ) notes = " | ".join(notes_candidates) if notes_candidates else None return ExecutivePlaybook( headline= f"{diagnostics.stage.title()} momentum for {diagnostics.focus} with autonomous orchestration", focus=diagnostics.focus, urgency=diagnostics.urgency, north_star_metric=north_star_metric, total_budget_usd=round(budget.total_budget, 2) if budget else None, expected_revenue_usd=round(budget.expected_revenue, 2) if budget else None, confidence=overall_confidence, directives=directives, summary=summary, notes=notes, ) @lru_cache(maxsize=1) def default_marketing_engine() -> MarketingIntelligenceEngine: return MarketingIntelligenceEngine.from_file()