#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Opt-in, project-local workaround for duplicate SwiftBridging module maps.
Does not change Apple toolchain files or REA code. Run from the case workspace.
"""
import json
import platform
import re
import shlex
import subprocess
from pathlib import Path

if platform.system() != 'Darwin':
    raise SystemExit('This workaround is only for the documented macOS failure.')
swiftc = Path(subprocess.check_output(['xcrun', '--find', 'swiftc'], text=True).strip()).absolute()
sdk = Path(subprocess.check_output(['xcrun', '--show-sdk-path'], text=True).strip()).resolve()
include = swiftc.parent.parent / 'include' / 'swift'
legacy, current = include / 'module.modulemap', include / 'bridging.modulemap'
def body(path):
    text = re.sub(r'/\*.*?\*/', '', path.read_text(), flags=re.S)
    text = re.sub(r'//[^\n]*', '', text)
    return re.sub(r'\s+', '', text)
expected = 'moduleSwiftBridging{header"bridging"export*}'
if not (legacy.is_file() and current.is_file()):
    raise SystemExit('Duplicate files not found. Do not apply this workaround.')
if body(legacy) != expected or body(current) != expected:
    raise SystemExit('Module definitions differ from the verified case; refusing to mask them.')
root = (Path.cwd() / '.rea-local').resolve()
root.mkdir(exist_ok=True)
empty = root / 'empty.modulemap'
empty.write_text('// Only the verified duplicate legacy declaration is hidden for this compilation.\n')
overlay = root / 'swift-overlay.json'
overlay.write_text(json.dumps({'version': 0, 'roots': [{'type': 'file', 'name': str(legacy), 'external-contents': str(empty)}]}, indent=2))
wrapper = root / 'swiftc-rea'
wrapper.write_text('#!/bin/sh\nexec ' + shlex.quote(str(swiftc)) + ' -vfsoverlay ' + shlex.quote(str(overlay)) + ' "$@"\n')
wrapper.chmod(0o755)
env = root / 'env.sh'
env.write_text('export REA_DARWIN_SWIFTC_PATH=' + shlex.quote(str(wrapper)) + '\nexport SDKROOT=' + shlex.quote(str(sdk)) + '\nexport REA_DARWIN_MODULE_CACHE_PATH=' + shlex.quote(str(root / 'module-cache')) + '\n')
print('Created a local compiler wrapper after verifying identical module definitions.')
print('Activate only in the current shell: source .rea-local/env.sh')
print('To stop using it, open a new terminal (no shell profile is modified).')
