from pathlib import Path
from jinja2 import Environment, FileSystemLoader, StrictUndefined

from iriusrisk_drl_toolkit.models import RelationRule

TEMPLATE_DIR = Path(__file__).resolve().parent.parent.parent / "templates"

DEFAULT_IMPORTS = [
    "com.iriusrisk.model.Component",
    "com.iriusrisk.model.Relation",
    "com.acme.iriusrisk.actions.RuleActions",
]


def build_jinja_env() -> Environment:
    return Environment(
        loader=FileSystemLoader(str(TEMPLATE_DIR)),
        undefined=StrictUndefined,
        trim_blocks=True,
        lstrip_blocks=True,
    )


def generate_drl(
    rule: RelationRule,
    package_name: str = "com.acme.iriusrisk.custom",
    imports: list[str] | None = None,
) -> str:
    env = build_jinja_env()
    template = env.get_template("relation_activity_rule.drl.j2")

    rendered = template.render(
        package_name=package_name,
        imports=imports or DEFAULT_IMPORTS,
        rule=rule,
    )

    return rendered.strip() + "\n"
