#!/usr/bin/env python3
"""
Seed-Runner: legt die in ``compliance.data.template_rule_seed_data.SEED_RULES``
definierten Regeln als published Versionen in ``compliance_template_rules`` an.

Idempotent über ``rule_key`` — wiederholtes Ausführen erzeugt keine Duplikate.
Quellen-Citation = ``rationale`` als Default (anwaltlich zu prüfen).
"""

from __future__ import annotations

import os
import sys
from datetime import datetime, timezone

# Pfad-Setup für Standalone-Ausführung
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from classroom_engine.database import SessionLocal  # noqa: E402
from compliance.data.template_rule_seed_data import SEED_RULES  # noqa: E402
from compliance.db.template_rule_models import (  # noqa: E402
    TemplateRuleDB,
    TemplateRuleVersionDB,
    TemplateRuleApprovalDB,
)


def seed() -> None:
    db = SessionLocal()
    try:
        created = 0
        skipped = 0
        for entry in SEED_RULES:
            existing = (
                db.query(TemplateRuleDB)
                .filter(TemplateRuleDB.rule_key == entry["rule_key"])
                .first()
            )
            if existing:
                skipped += 1
                continue

            rule = TemplateRuleDB(
                rule_key=entry["rule_key"],
                document_type=entry["document_type"],
                title=entry["title"],
            )
            db.add(rule)
            db.flush()

            now = datetime.now(timezone.utc)
            version = TemplateRuleVersionDB(
                rule_id=rule.id,
                version_number=1,
                status="published",
                is_live=1,
                classification=entry["classification"],
                conditions=entry["conditions"],
                source_citation=entry.get("rationale", "TODO — anwaltlich zu pruefen"),
                rationale=entry.get("rationale"),
                change_summary="Initial-Seed der Inline-Regeln",
                created_by="seed",
                submitted_by="seed",
                submitted_at=now,
                approved_by="seed",
                approved_at=now,
                published_by="seed",
                published_at=now,
            )
            db.add(version)
            db.flush()

            rule.current_version_id = version.id

            for action in ("created", "submitted", "approved", "published"):
                db.add(TemplateRuleApprovalDB(
                    version_id=version.id, action=action, approver="seed",
                ))

            created += 1

        db.commit()
        print(f"OK created={created} skipped={skipped} (already present)")
    finally:
        db.close()


if __name__ == "__main__":
    seed()
