#!/usr/bin/env python
"""
Build script for the AMY Synthesizer GDExtension.

AMY C source lookup order:
  1. AMY_SRC_PATH environment variable (if set)
  2. ../src/  (AMY repo source, when building from the repo)
  3. ./amy_src/  (vendored source, when installed via setup_godot.sh)
"""
import os
import sys

# Find godot-cpp
godot_cpp_path = os.environ.get("GODOT_CPP_PATH", os.path.join(os.path.dirname(os.path.abspath(".")), "godot-cpp"))

# Find AMY C source: env var > repo source > vendored copy
amy_src_path = os.environ.get("AMY_SRC_PATH", None)
if amy_src_path is None:
    # Try repo layout first (godot/ is sibling to src/)
    repo_src = os.path.join(os.path.dirname(os.path.abspath(".")), "src")
    if os.path.isdir(repo_src):
        amy_src_path = repo_src
    elif os.path.isdir("amy_src"):
        amy_src_path = "amy_src"
    else:
        print("ERROR: AMY source not found. Either:")
        print("  - Build from the AMY repo (godot/ directory)")
        print("  - Place AMY source in amy_src/")
        print("  - Or set AMY_SRC_PATH environment variable")
        Exit(1)

env = SConscript(os.path.join(godot_cpp_path, "SConstruct"))

# AMY C source files (core synthesis - no platform-specific I2S, no example mains)
amy_sources = [
    "algorithms.c",
    "amy.c",
    "api.c",
    "custom.c",
    "delay.c",
    "envelope.c",
    "examples.c",
    "filters.c",
    "instrument.c",
    "interp_partials.c",
    "log2_exp2.c",
    "midi_mappings.c",
    "oscillators.c",
    "parse.c",
    "patches.c",
    "pcm.c",
    "sequencer.c",
    "transfer.c",
]

# Add AMY include path
env.Append(CPPPATH=[amy_src_path])

# AMY compile flags
env.Append(CCFLAGS=["-DAMY_WAVETABLE", "-DAMY_NO_MINIAUDIO"])

# Suppress warnings from AMY's C code (GCC/Clang vs MSVC)
is_msvc = env.get("is_msvc", False) or (env["platform"] == "windows" and not env.get("use_mingw", False))
if is_msvc:
    env.Append(CFLAGS=["/std:c11", "/wd4244", "/wd4267", "/wd4996", "/wd4100"])
else:
    env.Append(CFLAGS=["-Wno-unused-parameter", "-Wno-sign-compare", "-Wno-missing-field-initializers"])

# Platform-specific flags (use target platform, not build machine)
target_platform = env["platform"]
if target_platform == "macos":
    env.Append(CCFLAGS=["-DMACOS"])
    env.Append(LINKFLAGS=["-framework", "CoreFoundation"])
elif target_platform == "linux":
    env.Append(LIBS=["pthread", "m"])
elif target_platform == "windows":
    if is_msvc:
        env.Append(CCFLAGS=["-DWINDOWS"])
    else:
        env.Append(CCFLAGS=["-DWINDOWS"])

# Build all sources together - AMY C files + GDExtension C++ files
all_sources = []

for src in amy_sources:
    src_path = os.path.join(amy_src_path, src)
    if os.path.exists(src_path):
        all_sources.append(src_path)

# GDExtension C++ sources + platform stubs
all_sources += [
    "src/amy_platform_stubs.c",
    "src/amy_gdextension.cpp",
    "src/register_types.cpp",
]

# Add our source include path
env.Append(CPPPATH=["src"])

# Build shared library directly from all sources
if target_platform == "macos":
    # Build as dylib for macOS (not framework - NSBundle crashes on macOS 26+)
    # godot-cpp strips SHLIBSUFFIX for macOS framework builds, so add .dylib explicitly
    library = env.SharedLibrary(
        target="bin/libamy{}.dylib".format(env["suffix"]),
        source=all_sources,
    )
else:
    library = env.SharedLibrary(
        target="bin/libamy{}{}".format(env["suffix"], env["SHLIBSUFFIX"]),
        source=all_sources,
    )

Default(library)
