import xml.etree.ElementTree as ET
import subprocess
import os

csproj_path = 'Newdelhibarassocia.csproj'
tree = ET.parse(csproj_path)
root = tree.getroot()

# MSBuild XML namespace
ns = {'ns': 'http://schemas.microsoft.com/developer/msbuild/2003'}

compile_files = []
for compile_elem in root.findall('.//ns:Compile', ns):
    include_val = compile_elem.attrib.get('Include')
    if include_val and include_val.endswith('.cs'):
        # Normalize backslashes to forward slashes for Linux compatibility
        include_val = include_val.replace('\\', '/')
        if os.path.exists(include_val):
            compile_files.append(include_val)
        else:
            print(f"Warning: File not found: {include_val}")

print(f"Found {len(compile_files)} files to compile.")

# Construct mcs command targeting Mono 4.5/4.7.2 compatible APIs
cmd = [
    'mcs',
    '-target:library',
    '-out:bin/Newdelhibarassocia.dll',
    '-r:/usr/lib/mono/4.5/System.dll',
    '-r:/usr/lib/mono/4.5/System.Web.dll',
    '-r:/usr/lib/mono/4.5/System.Data.dll',
    '-r:/usr/lib/mono/4.5/System.Configuration.dll',
    '-r:/usr/lib/mono/4.5/System.Web.Extensions.dll',
    '-r:/usr/lib/mono/4.5/System.Web.Services.dll',
    '-r:/usr/lib/mono/4.5/System.Xml.dll',
    '-r:/usr/lib/mono/4.5/System.Xml.Linq.dll',
    '-r:/usr/lib/mono/4.5/System.Drawing.dll',
    '-r:/usr/lib/mono/4.5/System.Core.dll',
    '-r:bin/Newtonsoft.Json.dll',
    '-r:bin/AjaxControlToolkit.dll',
    '-r:bin/itextsharp.dll',
    '-r:bin/getepay-sdk.dll'
] + compile_files

print("Running Mono compiler (mcs)...")
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if result.returncode == 0:
    print("✅ COMPILATION SUCCESSFUL! bin/Newdelhibarassocia.dll created.")
else:
    print("❌ COMPILATION FAILED:")
    print(result.stdout)
    print(result.stderr)
