from __future__ import annotations

from agent_sentinel import SentinelRunner, Guardrails, DecisionPolicy, ConfidenceInputs
from agent_sentinel.policies import load_policy
from agent_sentinel.procurement import ProcurementLeakageAnalyzer
from agent_sentinel.roi.report import build_finops_roi_report
from agent_sentinel.roi.executive import build_executive_brief
from agent_sentinel.runtime.artifacts import create_artifact_dir, write_manifest


BUSINESS_CONTEXT = {
    "program": "Procurement Spend Leakage",
    "business_unit": "Shared Services",
    "reporting_period": "2026-01",
    "currency": "USD",
    "assumptions": [
        "Savings represent recoverable leakage",
        "No payments halted automatically",
        "Findings require AP approval",
    ],
}


def procurement_agent(ctx, payload):
    ctx.add_cost(payload.get("estimated_cost_usd", 0.02))
    policy = load_policy("procurement_policy.yaml", override_path=payload.get("policy_path"))
    analyzer = ProcurementLeakageAnalyzer(policy=policy, business_context=BUSINESS_CONTEXT)
    return analyzer.analyze(payload)


def main(policy_path=None, outdir=None):
    policy = load_policy("procurement_policy.yaml", override_path=policy_path)

    runner = SentinelRunner(
        name="procurement_spend_leakage",
        guardrails=Guardrails(**policy.data["guardrails"]),
        decision_policy=DecisionPolicy(**policy.data["decision_policy"]),
        metadata=BUSINESS_CONTEXT,
    )

    payload = {
        "estimated_cost_usd": 0.02,
        "policy_path": policy_path,
        "approved_vendors": ["ACME_SUPPLY"],
        "baseline_unit_prices": {"SKU-123": 10.0},
        "invoices": [
            {"record_id": "1", "vendor": "ACME_SUPPLY", "invoice_id": "INV-1",
             "amount_usd": 5200, "sku": "SKU-123", "qty": 500, "unit_price_usd": 10.4},
            {"record_id": "2", "vendor": "ACME_SUPPLY", "invoice_id": "INV-1",
             "amount_usd": 5200, "sku": "SKU-123", "qty": 500, "unit_price_usd": 10.4},
        ],
    }

    confidence = ConfidenceInputs(prob=0.86, margin=0.20, z_score=1.8, entropy=0.32, llm_self_score=0.82)
    result = runner.run(procurement_agent, payload, confidence_inputs=confidence)

    artifacts = create_artifact_dir("procurement") if outdir is None else outdir
    report = build_finops_roi_report(
    sentinel_result=result,
    agent_output=result.output,
    title="Procurement Spend Leakage ROI Report",
)
    brief = build_executive_brief(
        title="Procurement Spend Leakage — Executive Brief",
        business_context=BUSINESS_CONTEXT,
        sentinel_result=result,
        agent_output=result.output,
    )

    analyzer = ProcurementLeakageAnalyzer(policy=policy, business_context=BUSINESS_CONTEXT)
    analyzer.export_recommendations_csv(result.output, f"{artifacts}/recommendations.csv")

    with open(f"{artifacts}/roi_report.md", "w", encoding="utf-8") as f:
        f.write(report.to_markdown())
    with open(f"{artifacts}/executive_brief.md", "w", encoding="utf-8") as f:
        f.write(brief)

    write_manifest(
        artifact_dir=artifacts,
        demo_name="procurement",
        business_context=BUSINESS_CONTEXT,
        decision_outcome=result.outcome.value,
        confidence=result.confidence,
    )

    print(f"\nArtifacts written to: {artifacts}\n")
