//! BalancedDepthScanPolicyBox (Phase 107)
//!
//! Responsibility:
//! - Provide a single SSOT entry point for the balanced depth-scan policy decision
//!   so callers (routing/apply) don't duplicate Use/Reject/None handling.

use crate::ast::ASTNode;

use super::balanced_depth_scan_policy::{
    classify_balanced_depth_scan_array_end, classify_balanced_depth_scan_object_end,
    BalancedDepthScanPolicyResult,
};
use super::PolicyDecision;

pub(crate) struct BalancedDepthScanPolicyBox;

impl BalancedDepthScanPolicyBox {
    pub(crate) fn decide(
        condition: &ASTNode,
        body: &[ASTNode],
    ) -> PolicyDecision<BalancedDepthScanPolicyResult> {
        // Try known balanced families. Order is SSOT.
        // - array: `[` ... `]`
        // - object: `{` ... `}`
        //
        // IMPORTANT: `Reject` means "close-but-unsupported" for that family, not "not this family".
        // We only return `Reject` if no other family matches.
        let array = classify_balanced_depth_scan_array_end(condition, body);
        let decision = match array {
            PolicyDecision::Use(_) => array,
            PolicyDecision::Reject(_) => {
                let object = classify_balanced_depth_scan_object_end(condition, body);
                match object {
                    PolicyDecision::Use(_) => object,
                    PolicyDecision::Reject(_) => array,
                    PolicyDecision::None => array,
                }
            }
            PolicyDecision::None => classify_balanced_depth_scan_object_end(condition, body),
        };

        if crate::config::env::joinir_dev_enabled() {
            use crate::mir::builder::control_flow::joinir::trace;
            let summary = match &decision {
                PolicyDecision::Use(_) => "Use".to_string(),
                PolicyDecision::Reject(reason) => format!("Reject: {}", reason),
                PolicyDecision::None => "None".to_string(),
            };
            trace::trace().dev("phase107/balanced_depth_scan_policy", &summary);
        }

        decision
    }
}
