"""
Nsc410 核心编译器
"""
from numexpr import *
from Nsc371 import *
import re

def Ns4ev(eval_sif, space=None):
    """Ns4ev->es"""
    if space == True:
        pass
    else:
        eval_sif = eval_sif.replace(' ', '')
    
    # 处理原始字符串 (r-string)
    if eval_sif.startswith(('r"', "r'")) and eval_sif.endswith(('"', "'")):
        return eval_sif[2:-1]
    
    # 处理字节字符串 (b-string)
    if eval_sif.startswith(('b"', "b'")) and eval_sif.endswith(('"', "'")):
        return eval(eval_sif)
    
    # 处理格式化字符串 (f-string)
    if eval_sif.startswith(('f"', "f'")) and eval_sif.endswith(('"', "'")):
        quote_char = eval_sif[1]
        f_content = eval_sif[2:-1]
        
        # 匹配 {} 中的表达式
        pattern = r'\{([^}]+)\}'
        matches = re.findall(pattern, f_content)
        
        for expr in matches:
            try:
                result = str(evaluate(expr))
                f_content = f_content.replace('{' + expr + '}', result)
            except Exception as e:
                raise SyntaxError(f'Error: Nsc410 f-string expression "{expr}" is wrong: {e}')
        return f_content
    
    # 处理多行字符串 (三重引号)
    if eval_sif.startswith(('"""', "'''")) and eval_sif.endswith(('"""', "'''")):
        return eval_sif[3:-3]
    
    # 处理普通字符串拼接
    if '"' in eval_sif or "'" in eval_sif:
        # 确定引号类型
        if '"' in eval_sif and "'" in eval_sif:
            if eval_sif.count('"') > eval_sif.count("'"):
                quote_char = '"'
            else:
                quote_char = "'"
        elif '"' in eval_sif:
            quote_char = '"'
        else:
            quote_char = "'"
        
        # 分割并处理字符串
        list_es = eval_sif.split(quote_char)
        list_es = [i for i in list_es if i != '' and i != '+']
        result = ''.join(list_es)
        
        # 处理转义字符
        result = (result.replace('\\n', '\n')
                       .replace('\\t', '\t')
                       .replace('\\r', '\r')
                       .replace('\\\\', '\\'))
        return result
    
    # 处理其他表达式
    try:
        return evaluate(eval_sif)
    except Exception:
        raise SyntaxError(f'Error:Nsc410 expr{eval_sif} is wrong.')
