#!/usr/bin/env python3
"""Reproduce the private GCC 16.2.0 frontend from the versioned compiler patches."""

import argparse
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile


ROOT = Path(__file__).resolve().parents[1]
PATCHES = ROOT / "compiler-patches/gcc-16.2.0"
VERSION = "16.2.0"
TOOLS = {"CC": "gcc", "CXX": "g++", "AR": "ar", "AS": "as", "LD": "ld", "NM": "nm",
         "RANLIB": "ranlib", "STRIP": "strip", "OBJCOPY": "objcopy", "OBJDUMP": "objdump",
         "READELF": "readelf"}
OPTIMIZATION = {"CFLAGS": "-O1 -g1", "CXXFLAGS": "-O1 -g1"}


def configure_options(prefix):
    lines = (PATCHES / "configure.args").read_text(encoding="utf-8").splitlines()
    text = " ".join(line for line in lines if line and not line.startswith("#"))
    return shlex.split(text.replace("@PREFIX@", str(prefix)))


def patch_state(source, patch):
    """Forward and reverse dry runs distinguish a pristine, applied or foreign tree."""
    base = ["patch", "--dry-run", "-p1", "--directory", str(source), "-i", str(patch)]
    if subprocess.run([*base, "--forward"], capture_output=True).returncode == 0:
        return "unpatched"
    if subprocess.run([*base, "--reverse"], capture_output=True).returncode == 0:
        return "already-applied"
    return "mismatch"


def validate_series(source, patches):
    """Apply the ordered series to a scratch copy: patches depend on their predecessors."""
    with tempfile.TemporaryDirectory(prefix="vls-gcc-series-") as temp:
        scratch = Path(temp) / "source"
        shutil.copytree(source, scratch, symlinks=True)
        results = []
        for patch in patches:
            if patch_state(scratch, patch) == "already-applied":
                results.append((patch.name, True))
                continue
            applied = subprocess.run(
                ["patch", "-p1", "--directory", str(scratch), "-i", str(patch)],
                capture_output=True)
            results.append((patch.name, applied.returncode == 0))
            if applied.returncode != 0:
                break
        return results


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, default=Path("build/gcc-gate/gcc-16.2.0"),
                        help="GCC 16.2.0 source tree")
    parser.add_argument("--output", type=Path, default=Path("build/private-gcc"),
                        help="private build root (source copy, build and install)")
    parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1)
    parser.add_argument("--check-only", action="store_true",
                        help="validate the source and patch set, print the recipe, build nothing")
    args = parser.parse_args()
    try:
        source = args.source.resolve(strict=True)
        version = source / "gcc/BASE-VER"
        if not version.is_file() or version.read_text(encoding="utf-8").strip() != VERSION:
            raise ValueError(f"expected a GCC {VERSION} source tree at {source}")
        patches = sorted(PATCHES.glob("*.patch"))
        if not patches:
            raise ValueError(f"no patches under {PATCHES}")
        states = {}
        for patch in patches:
            states[patch.name] = patch_state(source, patch)
            print(f"{patch.name}: {states[patch.name]}")
        if not args.check_only and any(state == "mismatch" for state in states.values()):
            raise ValueError("the patch set does not match this source tree")
        prefix = args.output.absolute() / "install"
        command = [str(source / "configure"), *configure_options(prefix)]
        print("configure:", shlex.join(command))
        if args.check_only:
            series = validate_series(source, patches)
            for name, ok in series:
                print(f"series {name}: {'ok' if ok else 'failed'}")
            if len(series) != len(patches) or not all(ok for _, ok in series):
                raise ValueError("the ordered patch series does not apply")
            print(f"check passed: {len(patches)} patches, GCC {VERSION}, prefix {prefix}")
            return 0
        output = args.output.absolute()
        tree, build = output / "source", output / "build"
        if output.exists():
            raise ValueError(f"output already exists: {output}")
        shutil.copytree(source, tree, symlinks=True)
        for patch in patches:
            if states[patch.name] == "already-applied":
                continue
            subprocess.run(["patch", "-p1", "--directory", str(tree), "-i", str(patch)],
                           check=True)
        build.mkdir(parents=True)
        environment = {**os.environ, **TOOLS, **OPTIMIZATION}
        subprocess.run(command, cwd=build, env=environment, check=True)
        subprocess.run(["make", f"-j{args.jobs}"], cwd=build, check=True)
        print(f"private GCC built under {build}; selected frontend is in gcc/cc1plus")
        return 0
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        print(f"prepare-private-gcc: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
