
import subprocess
import datetime
import pathlib

try:
    import tomllib  # Python 3.11+
except Exception:  # pragma: no cover - older Pythons
    tomllib = None

root = pathlib.Path(__file__).resolve().parents[1]
# templates live inside the backend package
template = root / "sls_build_backend" / "_version.py.in"
template_dev = root / "sls_build_backend" / "_version_dev.py.in"
output = root / "sls_py" / "_version.py"


def get_commit():
    try:
        result_hash = subprocess.check_output(
            ["git", "describe", "--always", "--dirty", "--abbrev=7"],
            cwd=str(root),
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()
        result_date = subprocess.check_output(
            ["git", "show", "-s", "--format=%ci"],
            cwd=str(root),
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()
        return f"{result_hash} {result_date}"
    except Exception:
        return "unknown"


def get_timestamp():
    return datetime.datetime.now(datetime.timezone.utc).isoformat() + "Z"


def _get_version_from_pyproject(root_path: pathlib.Path):
    py = root_path / "pyproject.toml"
    if not py.exists() or tomllib is None:
        return None
    try:
        data = tomllib.loads(py.read_text())
    except Exception:
        return None
    # PEP 621
    version = data.get("project", {}).get("version")
    if version:
        return version
    # Some projects put metadata under tool.setuptools
    version = data.get("tool", {}).get("setuptools", {}).get("version")
    return version


def _determine_version(root_path: pathlib.Path):
    v = _get_version_from_pyproject(root_path)
    if v:
        return v
    return "unknown"


def generate_version_dev():
    version = _determine_version(root)
    if not template_dev.exists():
        # write a minimal generated file if dev template missing
        output.write_text(f"version = \"{version}\"\ncommit = \"unknown\"\ntimestamp = \"unknown\"\n")
        return
    text = template_dev.read_text()
    text = text.format(version=version)
    output.write_text(text)


def generate_version():
    version = _determine_version(root)

    commit = get_commit()
    timestamp = get_timestamp()

    if not template.exists():
        # fallback: write a minimal file
        output.write_text(
            f"version = \"{version}\"\ncommit = \"{commit}\"\ntimestamp = \"{timestamp}\"\n"
        )
        return

    text = template.read_text()
    text = text.format(version=version, commit=commit, timestamp=timestamp)
    output.write_text(text)
