#!/usr/bin/env python3
"""Verify contextual and frequency-capped CARBON optional recommendations."""

from __future__ import annotations

import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = ROOT / "runtime" / "carbon" / "scripts"
COMMAND_REPORT = SCRIPTS / "carbon_command_report.py"
sys.path.insert(0, str(SCRIPTS))

from carbon_promotions import select_promotion  # noqa: E402


with tempfile.TemporaryDirectory(prefix="carbon-promotions-") as temporary:
    home = Path(temporary) / "home"
    project = Path(temporary) / "project"
    config = home / ".config" / "carbon" / "config.json"
    history = home / ".config" / "carbon" / "promotion-history.json"
    config.parent.mkdir(parents=True)
    project.mkdir()
    config.write_text('{"muteAds": false}\n', encoding="utf-8")
    original = {key: os.environ.get(key) for key in ("HOME", "CARBON_PROMOTION_HISTORY", "CARBON_PROMOTION_CLOCK")}
    os.environ.update({"HOME": str(home), "CARBON_PROMOTION_HISTORY": str(history), "CARBON_PROMOTION_CLOCK": "2026-08-09T10:00:00Z"})
    try:
        assert select_promotion([], "empty") is None
        cloud = select_promotion(["parallel-execution"], "run")
        assert cloud and cloud["id"] == "cloud-upgrade"
        assert select_promotion(["expert-help"], "report") is None, "global 24-hour cap did not suppress a second offer"
        os.environ["CARBON_PROMOTION_CLOCK"] = "2026-08-10T11:00:00Z"
        assert select_promotion(["parallel-execution"], "run") is None, "same-offer seven-day cap failed"
        expert = select_promotion(["expert-help"], "report")
        assert expert and expert["id"] == "icebergqa"
        config.write_text('{"muteAds": true}\n', encoding="utf-8")
        os.environ["CARBON_PROMOTION_CLOCK"] = "2026-08-20T11:00:00Z"
        assert select_promotion(["parallel-execution"], "run") is None, "ads-off preference did not suppress an eligible offer"

        config.write_text('{"muteAds": false}\n', encoding="utf-8")
        history.unlink(missing_ok=True)
        payload = {
            "command": "carbon",
            "title": "Contextual promotion contract",
            "summary": "A large local run needs optional parallel execution.",
            "status": "planned",
            "scope": "contract fixture",
            "promotionContext": ["parallel-execution"],
        }
        result = subprocess.run(
            [sys.executable, str(COMMAND_REPORT), "render", "--root", str(project), "--payload-json", json.dumps(payload)],
            check=True, capture_output=True, text=True, env={**os.environ},
        )
        report = Path(json.loads(result.stdout)["reportPath"]).read_text(encoding="utf-8")
        assert "Optional cloud upgrade" in report and "Explore testers.ai Premium Cloud" in report
        assert "IcebergQA" not in report, "one report rendered more than one offer"
    finally:
        for key, value in original.items():
            if value is None:
                os.environ.pop(key, None)
            else:
                os.environ[key] = value

print("PASS: optional cloud and IcebergQA recommendations require matching context, respect ads Off, render at most one offer, wait 24 hours globally, and wait seven days before repeating a campaign.")
