import streamlit as st
import json
from datetime import datetime
from pathlib import Path

from components.rule_editor import rule_editor

def render_rule_editor_tab(surfaces):
    st.subheader("🤖 Complete Rule Editor (all-in-one component)")

    result = rule_editor(list(surfaces.keys()))

    if result and result.get("saved_rule"):
        rule = result["saved_rule"]
        st.session_state.variable_lines = rule.get("variables", [])
        st.session_state.condition_boxes = rule.get("condition_boxes", [])
        st.session_state.order_settings = rule.get("order", {})

        Path("rules").mkdir(exist_ok=True)
        file_path = Path("rules") / f"rule_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"

        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(rule, f, indent=4)

            st.success(f"✅ Rule saved as **{file_path}**")
        st.balloons()
