# Released under the MIT License. See LICENSE for details.
#
"""Functionality related to android builds."""
from __future__ import annotations

import os
import sys
import stat
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    pass

if __name__ == '__main__':

    from efrotools.project import (
        getprojectconfig,
        get_public_legal_notice,
        get_non_public_legal_notice,
    )

    # We expect 3 args: tool-name, tool-module, output-path
    if len(sys.argv) != 4:
        raise RuntimeError('Expected 3 args')
    toolname = sys.argv[1]
    toolmodule = sys.argv[2]
    outpath = sys.argv[3]

    # We technically could stick the 'python' or 'python3' path in, but
    # let's go with the full versioned one just to keep it clear what
    # we're using currently. Just need to make sure this gets re-run
    # when that changes.
    pybinpath = os.path.join(
        os.path.abspath(os.getcwd()), '.venv', 'bin', 'python3.12'
    )

    public = getprojectconfig(projroot='.').get('public', False)
    assert isinstance(public, bool)

    legalnotice: str = (
        get_public_legal_notice('raw')
        if public
        else get_non_public_legal_notice()
    )
    contents = (
        f'#!{pybinpath}\n'
        f'# {legalnotice}\n'
        f'# This file is autogenerated; do not edit.\n'
        f'#\n'
        f'"""Simple wrapper so {toolname} uses the project virtual'
        f' environment."""\n'
        f'from {toolmodule} import run_{toolname}_main\n'
        f'\n'
        f'if __name__ == "__main__":\n'
        f'    run_{toolname}_main()\n'
    )

    with open(outpath, 'w', encoding='utf-8') as outfile:
        outfile.write(contents)
    os.chmod(
        outpath,
        os.stat(outpath).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH,
    )
