#!/usr/bin/env python3
import json

from iriusrisk_drl_toolkit.models import (
    RelationRule,
    Activity,
    SvgObject,
    SvgRelation,
)
from iriusrisk_drl_toolkit.generator import generate_drl
from iriusrisk_drl_toolkit.parser import parse_relation_rule
from iriusrisk_drl_toolkit.explainer import evaluate_rule


def demo():
    rule = RelationRule(
        name="Create threat when process connects to database",
        source_type="process",
        relation_type="connects_to",
        target_type="database",
        activity=Activity(
            kind="CREATE_THREAT",
            value="SQL Injection",
        ),
        salience=50,
        no_loop=False,
        origin="custom",
        editable=True,
    )

    drl = generate_drl(rule, package_name="com.acme.iriusrisk.custom")
    print("=== GENERATED DRL ===")
    print(drl)

    parsed = parse_relation_rule(drl)
    print("=== PARSED RULE ===")
    print(parsed)
    print()

    src = SvgObject(id="A1", type="process", label="Backend API")
    rel = SvgRelation(source_id="A1", target_id="B1", relation_type="connects_to")
    dst = SvgObject(id="B1", type="database", label="Customer DB")

    result = evaluate_rule(parsed, src, rel, dst)
    print("=== EVALUATION (matching) ===")
    print(f"Applies: {result.applies}")
    print(f"Reasons: {result.reasons}")
    print(f"Failed: {result.failed}")
    print(f"JSON: {json.dumps({'applies': result.applies, 'reasons': result.reasons, 'failed': result.failed}, indent=2)}")
    print()

    src2 = SvgObject(id="A1", type="service", label="Auth Service")
    dst2 = SvgObject(id="B2", type="queue", label="Event Queue")

    result2 = evaluate_rule(parsed, src2, rel, dst2)
    print("=== EVALUATION (non-matching) ===")
    print(f"Applies: {result2.applies}")
    print(f"Reasons: {result2.reasons}")
    print(f"Failed: {result2.failed}")
    print(f"JSON: {json.dumps({'applies': result2.applies, 'reasons': result2.reasons, 'failed': result2.failed}, indent=2)}")
    print()

    platform_drl = """package com.iriusrisk.platform

import com.iriusrisk.model.Component
import com.iriusrisk.model.Relation
import com.iriusrisk.actions.RuleActions

rule "Vendor: create countermeasure for public endpoint"
    salience 100
when
    $rel : Relation(
        relationType == "exposes",
        $srcId : sourceId,
        $dstId : targetId
    )

    $src : Component(
        id == $srcId,
        type == "load_balancer"
    )

    $dst : Component(
        id == $dstId,
        type == "endpoint"
    )
then
    RuleActions.createActivity(
        "CREATE_COUNTERMEASURE",
        $dst,
        "WAF"
    );
end"""

    platform_rule = parse_relation_rule(
        platform_drl,
        origin="platform",
        editable=False,
    )
    print("=== PLATFORM RULE (greyed out in UI) ===")
    print(f"Name: {platform_rule.name}")
    print(f"Origin: {platform_rule.origin}")
    print(f"Editable: {platform_rule.editable}")
    print(f"Source type: {platform_rule.source_type}")
    print(f"Relation type: {platform_rule.relation_type}")
    print(f"Target type: {platform_rule.target_type}")
    print(f"Activity: {platform_rule.activity}")
    print()

    print("=== ROUND-TRIP VERIFICATION ===")
    assert parsed.name == rule.name
    assert parsed.source_type == rule.source_type
    assert parsed.relation_type == rule.relation_type
    assert parsed.target_type == rule.target_type
    assert parsed.activity.kind == rule.activity.kind
    assert parsed.activity.value == rule.activity.value
    assert parsed.salience == rule.salience
    print("All assertions passed — round-trip is clean.")


if __name__ == "__main__":
    demo()
