import os
import sys
import rtconfig
from SCons.Script import *

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.normpath(os.getcwd() + '/../../../..')

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]

try:
    from building import *
except:
    print('Cannot found RT-Thread root directory, please check RTT_ROOT')
    print(RTT_ROOT)
    exit(-1)

TARGET = 'rtthread.' + rtconfig.TARGET_EXT

DefaultEnvironment(tools=[])
env = Environment(tools = ['mingw'],
    AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
    CC = rtconfig.CC, CCFLAGS = rtconfig.CFLAGS,
    CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS,
    AR = rtconfig.AR, ARFLAGS = '-rc',
    LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS)
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
env['ASCOM'] = env['ASPPCOM']

Export('RTT_ROOT')
Export('rtconfig')

# prepare building environment
objs = PrepareBuilding(env, RTT_ROOT, has_libcpu = False)

stack_size = 4096

if GetDepend('RT_USING_SMART'):
    # use smart link.lds
    env['LINKFLAGS'] = env['LINKFLAGS'].replace('link.lds', 'link_smart.lds')

stack_lds = open('link_stacksize.lds', 'w')
if GetDepend('__STACKSIZE__'): stack_size = GetDepend('__STACKSIZE__')
stack_lds.write('__STACKSIZE__ = %d;\n' % stack_size)
stack_lds.close()

# Obtain the number of harts from rtconfig.h and write
# it into link_cpus.lds for the linker script
try:
    with open('rtconfig.h', 'r') as f:
        rtconfig_content = f.readlines()
except FileNotFoundError:
    cpus_nr = 1
else:
    cpus_nr = 1  # default value
    for line in rtconfig_content:
        line = line.strip()
        if line.startswith('#define') and 'RT_CPUS_NR' in line:
            parts = line.split()
            if len(parts) >= 3 and parts[2].isdigit():
                cpus_nr = int(parts[2])
                break

with open('link_cpus.lds', 'w') as cpus_lds:
    cpus_lds.write(f'RT_CPUS_NR = {cpus_nr};\n')

# make a building
DoBuilding(TARGET, objs)
