from __future__ import annotations

from agent_sentinel import SentinelRunner, Guardrails, DecisionPolicy, ConfidenceInputs
from agent_sentinel.policies import load_policy
from agent_sentinel.finops import FinOpsAnalyzer
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": "Cloud Cost Governance",
    "business_unit": "Enterprise Infrastructure",
    "reporting_period": "2026-01",
    "currency": "USD",
    "assumptions": [
        "Savings estimates are conservative",
        "No production changes executed automatically",
        "High-risk actions require owner approval",
        "All decisions are audited",
    ],
}


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


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

    runner = SentinelRunner(
        name="cloud_cost_governance",
        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,
        "resources": [
            {"id": "ec2-prod-payments-01", "type": "ec2_instance", "owner": "payments",
             "environment": "production", "monthly_cost_usd": 520, "utilization_pct": 6.2},
            {"id": "rds-prod-orders", "type": "rds_instance", "owner": "orders",
             "environment": "production", "monthly_cost_usd": 860, "utilization_pct": 2.0},
            {"id": "s3-central-logs", "type": "s3_bucket", "owner": "security",
             "environment": "shared", "monthly_cost_usd": 310, "storage_gb": 9200},
        ],
    }

    confidence = ConfidenceInputs(prob=0.84, margin=0.22, z_score=1.7, entropy=0.35, llm_self_score=0.8)
    result = runner.run(finops_agent, payload, confidence_inputs=confidence)

    artifacts = create_artifact_dir("finops") if outdir is None else outdir
    report = build_finops_roi_report(
    sentinel_result=result,
    agent_output=result.output,
    title="Cloud Cost Governance ROI Report",
)

    brief = build_executive_brief(
        title="Cloud Cost Governance — Executive Brief",
        business_context=BUSINESS_CONTEXT,
        sentinel_result=result,
        agent_output=result.output,
    )

    analyzer = FinOpsAnalyzer(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="finops",
        business_context=BUSINESS_CONTEXT,
        decision_outcome=result.outcome.value,
        confidence=result.confidence,
    )

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