#!/usr/bin/env python3
import json
import os
from typing import Any

import httpx


def env_bool(name: str, default: bool) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.lower() in {"1", "true", "yes", "on"}


IRIS_BASE_URL = os.getenv("IRIS_BASE_URL", "https://localhost:8443").rstrip("/")
IRIS_API_KEY = os.getenv("IRIS_API_KEY", "")
IRIS_VERIFY_SSL = env_bool("IRIS_VERIFY_SSL", False)
INTEGRATOR_URL = os.getenv("INTEGRATOR_URL", "http://localhost:8088").rstrip("/")


def pretty(title: str, payload: dict[str, Any]) -> None:
    print(f"\n=== {title} ===")
    print(json.dumps(payload, indent=2, default=str))


def direct_iris_create_case() -> None:
    url = f"{IRIS_BASE_URL}/api/v2/cases"
    headers = {"Authorization": f"Bearer {IRIS_API_KEY}"} if IRIS_API_KEY else {}
    payload = {
        "title": "Sample SOC case from direct IRIS API call",
        "description": "Created by soc-integrator/examples/iris_api_examples.py",
        "tags": ["soc", "sample", "direct-api"],
    }

    with httpx.Client(verify=IRIS_VERIFY_SSL, timeout=20.0) as client:
        response = client.post(url, json=payload, headers=headers)
        response.raise_for_status()
        data = response.json() if response.content else {"status_code": response.status_code}
    pretty("Direct IRIS API response", data)


def via_integrator_create_case() -> None:
    url = f"{INTEGRATOR_URL}/action/create-iris-case"
    payload = {
        "title": "Sample SOC case via integrator",
        "severity": "medium",
        "source": "soc-integrator-example",
        "payload": {
            "description": "Created through /action/create-iris-case",
            "tags": ["soc", "sample", "integrator-api"],
        },
    }

    with httpx.Client(timeout=20.0) as client:
        response = client.post(url, json=payload)
        response.raise_for_status()
        data = response.json() if response.content else {"status_code": response.status_code}
    pretty("Via integrator response", data)


if __name__ == "__main__":
    try:
        direct_iris_create_case()
    except Exception as exc:
        print(f"Direct IRIS call failed: {exc}")

    try:
        via_integrator_create_case()
    except Exception as exc:
        print(f"Integrator IRIS call failed: {exc}")
