#!/usr/bin/env python3
"""Private front-end entry point for the frontend-exec package."""
from pathlib import Path
import os
import subprocess
import sys

prefix = Path(__file__).resolve().parents[2]
python = prefix / 'tools/python'
if python.is_file() and python.resolve() != Path(sys.executable).resolve():
  os.execv(str(python.resolve()), [str(python.resolve()), str(Path(__file__).resolve()), *sys.argv[1:]])
if (prefix / 'sysconfig').is_dir():
  sys.path.insert(0, str(prefix / 'python' if (prefix / 'python').is_dir()
                         else prefix.parent.parent))
from curry import config
from curry.toolchain._analysisproducts import shipped_request
if shipped_request(sys.argv[1:]):
  sys.exit(0)
frontend = config.curry_frontend()
if not frontend:
  sys.exit('no Curry front end found; set SPRITE_FRONTEND or put pakcs-frontend on PATH')
# frontend-exec requests its compiler-named output directory. Its library
# lookup must still see the interfaces pinned for Sprite's selected front end.
# An interface-only view also keeps the front end from compiling library
# sources into the installation for a different output directory.
outdir = Path('.curry')
arguments = sys.argv[1:]
for index, argument in enumerate(arguments):
  if argument in ('-o', '--outdir') and index + 1 < len(arguments):
    outdir = Path(arguments[index + 1])
    if outdir.is_absolute():
      try:
        outdir = Path(os.path.relpath(outdir))
      except ValueError:
        pass
      arguments[index + 1] = str(outdir)
  elif argument.startswith('--outdir='):
    outdir = Path(argument.split('=', 1)[1])
    if outdir.is_absolute():
      try:
        outdir = Path(os.path.relpath(outdir))
      except ValueError:
        pass
      arguments[index] = '--outdir=' + str(outdir)
  elif argument in ('--no-outdir', '--no-subdir'):
    outdir = Path('.')
from curry.toolchain._interfaceview import interface_view
with interface_view(outdir) as library:
  sys.exit(subprocess.call([frontend, *config.frontend_flags().split(),
                            '-P', str(library), *arguments, '-i', str(library)]))
