import argparse
import subprocess
from pathlib import Path


def get_git_hash(root: Path) -> str:
    try:
        return subprocess.check_output(
            ["git", "rev-parse", "--short=8", "HEAD"],
            cwd=root,
            text=True
        ).strip()
    except Exception:
        return "unknown"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version", required=True)
    parser.add_argument("--revision", required=True)
    parser.add_argument("--build-number", required=True)


    args = parser.parse_args()

    ROOT = Path(__file__).resolve().parents[2]

    output = ROOT / "cc3d" / "_version.py"

    githash = get_git_hash(ROOT)

    content = f'''"""
This file is auto-generated by CMake.
Do NOT edit manually.
"""

__version__ = "{args.version}"
__revision__ = "{args.revision}"
__build_number__ = {args.build_number}
__githash__ = "{githash}"
'''

    output.write_text(content)

    print(f"Generated {output}")
    print(f"Version: {args.version}")
    print(f"Revision: {args.revision}")
    print(f"Build number: {args.build_number}")
    print(f"Git hash: {githash}")


if __name__ == "__main__":
    main()

