//! Phase 273 P1: PlanNormalizer - DomainPlan → CorePlan 変換 (SSOT)
//!
//! # Responsibilities
//!
//! - Convert DomainPlan to CorePlan (SSOT for pattern-specific knowledge)
//! - Generate ValueIds for CorePlan expressions
//! - Expand pattern-specific operations into generic CoreEffectPlan
//!
//! # Key Design Decision
//!
//! Normalizer is the ONLY place that knows pattern-specific semantics.
//! Lowerer processes CorePlan without any pattern knowledge.

mod helpers;
mod pattern1_simple_while;
mod pattern2_break;
mod pattern3_if_phi;
mod pattern4_continue;
mod pattern5_infinite_early_exit;
mod pattern8_bool_predicate_scan;
mod pattern9_accum_const_loop;
mod pattern_scan_with_init;
mod pattern_split_scan;
mod common;

use super::{
    CoreEffectPlan, CoreLoopPlan, CorePhiInfo, CorePlan, DomainPlan, Pattern1SimpleWhilePlan,
    Pattern2BreakPlan, Pattern3IfPhiPlan, Pattern4ContinuePlan, Pattern5ExitKind,
    Pattern5InfiniteEarlyExitPlan, Pattern8BoolPredicateScanPlan, Pattern9AccumConstLoopPlan,
    ScanWithInitPlan, SplitScanPlan,
};
use crate::mir::builder::control_flow::joinir::patterns::router::LoopPatternContext;
use crate::mir::builder::MirBuilder;

/// Phase 273 P1: PlanNormalizer - DomainPlan → CorePlan 変換 (SSOT)
pub(in crate::mir::builder) struct PlanNormalizer;

impl PlanNormalizer {
    /// Normalize DomainPlan to CorePlan
    ///
    /// This is the SSOT for pattern-specific knowledge expansion.
    /// All pattern semantics (scan, split, etc.) are expanded here.
    pub(in crate::mir::builder) fn normalize(
        builder: &mut MirBuilder,
        domain: DomainPlan,
        ctx: &LoopPatternContext,
    ) -> Result<CorePlan, String> {
        match domain {
            DomainPlan::ScanWithInit(parts) => Self::normalize_scan_with_init(builder, parts, ctx),
            DomainPlan::SplitScan(parts) => Self::normalize_split_scan(builder, parts, ctx),
            DomainPlan::Pattern4Continue(parts) => {
                Self::normalize_pattern4_continue(builder, parts, ctx)
            }
            DomainPlan::Pattern1SimpleWhile(parts) => {
                Self::normalize_pattern1_simple_while(builder, parts, ctx)
            }
            DomainPlan::Pattern9AccumConstLoop(parts) => {
                Self::normalize_pattern9_accum_const_loop(builder, parts, ctx)
            }
            DomainPlan::Pattern8BoolPredicateScan(parts) => {
                Self::normalize_pattern8_bool_predicate_scan(builder, parts, ctx)
            }
            DomainPlan::Pattern3IfPhi(parts) => Self::normalize_pattern3_if_phi(builder, parts, ctx),
            DomainPlan::Pattern2Break(parts) => Self::normalize_pattern2_break(builder, parts, ctx),
            DomainPlan::Pattern5InfiniteEarlyExit(parts) => {
                Self::normalize_pattern5_infinite_early_exit(builder, parts, ctx)
            }
        }
    }
}
