package org.jcnc.snow.compiler.semantic.analyzers.statement;

import org.jcnc.snow.compiler.parser.ast.FunctionNode;
import org.jcnc.snow.compiler.parser.ast.IfNode;
import org.jcnc.snow.compiler.semantic.analyzers.base.StatementAnalyzer;
import org.jcnc.snow.compiler.semantic.core.Context;
import org.jcnc.snow.compiler.semantic.core.ModuleInfo;
import org.jcnc.snow.compiler.semantic.error.SemanticError;
import org.jcnc.snow.compiler.semantic.symbol.SymbolTable;
import org.jcnc.snow.compiler.semantic.type.BuiltinType;
import org.jcnc.snow.compiler.semantic.type.Type;

/**
 * 改进版 {@code IfAnalyzer}，为 then/else 分支提供独立块级作用域。
 */
public class IfAnalyzer implements StatementAnalyzer<IfNode> {

    @Override
    public void analyze(Context ctx,
                        ModuleInfo mi,
                        FunctionNode fn,
                        SymbolTable locals,
                        IfNode ifn) {

        // 1. 条件类型检查
        var exprAnalyzer = ctx.getRegistry().getExpressionAnalyzer(ifn.condition());
        Type condType = exprAnalyzer.analyze(ctx, mi, fn, locals, ifn.condition());
        if (condType != BuiltinType.INT) {
            ctx.getErrors().add(new SemanticError(ifn, "if 条件必须为 int 类型(表示真假)"));
        }

        // 2. then 分支
        SymbolTable thenScope = new SymbolTable(locals);
        for (var stmt : ifn.thenBranch()) {
            var stAnalyzer = ctx.getRegistry().getStatementAnalyzer(stmt);
            if (stAnalyzer != null) {
                stAnalyzer.analyze(ctx, mi, fn, thenScope, stmt);
            } else {
                ctx.getErrors().add(new SemanticError(stmt, "不支持的语句类型: " + stmt));
            }
        }

        // 3. else 分支（可选）
        if (!ifn.elseBranch().isEmpty()) {
            SymbolTable elseScope = new SymbolTable(locals);
            for (var stmt : ifn.elseBranch()) {
                var stAnalyzer = ctx.getRegistry().getStatementAnalyzer(stmt);
                if (stAnalyzer != null) {
                    stAnalyzer.analyze(ctx, mi, fn, elseScope, stmt);
                } else {
                    ctx.getErrors().add(new SemanticError(stmt, "不支持的语句类型: " + stmt));
                }
            }
        }
    }
}