#!/usr/bin/env python3
"""Setup step for the sase split workflow."""

import os
import subprocess
import sys
from pathlib import Path


def main() -> None:
    """Run the setup step for split workflow."""
    from sase.ace.changespec import find_all_changespecs

    # Always get CL name from current branch
    cl_name = subprocess.run(
        ["branch_name"], capture_output=True, text=True, check=True
    ).stdout.strip()

    # Check for children (used to skip revert step)
    cs_list = find_all_changespecs()
    children = [
        cs for cs in cs_list if cs.parent == cl_name and cs.status != "Reverted"
    ]
    has_children = "true" if children else "false"

    # Get default parent
    target = next((cs for cs in cs_list if cs.name == cl_name), None)
    default_parent = target.parent if target and target.parent else "p4head"

    # Save diff from current branch
    os.makedirs("bb/sase", exist_ok=True)
    diff_path = f"bb/sase/{cl_name}.diff"
    with open(diff_path, "w") as f:
        result = subprocess.run(
            ["branch_diff"], capture_output=True, text=True, check=True
        )
        f.write(result.stdout)

    bug = subprocess.run(
        ["sase_hg_branch_bug"], capture_output=True, text=True, check=True
    ).stdout.strip()
    workspace = subprocess.run(
        ["workspace_name"], capture_output=True, text=True, check=True
    ).stdout.strip()

    print(f"cl_name={cl_name}")
    print(f"diff_path={diff_path}")
    print(f"bug={bug}")
    print(f"workspace_name={workspace}")
    print(f"default_parent={default_parent}")
    print(f"has_children={has_children}")


if __name__ == "__main__":
    main()
