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

import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Any


def _parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Prepare execute step for the sase split workflow"
    )
    parser.add_argument(
        "--spec",
        required=True,
        help="JSON spec array from generate_spec step",
    )
    parser.add_argument(
        "--cl-name",
        dest="cl_name",
        required=True,
        help="CL name being split",
    )
    parser.add_argument(
        "--default-parent",
        dest="default_parent",
        required=True,
        help="Default parent for the split CLs",
    )
    return parser.parse_args()


def _topological_sort(spec: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Sort spec entries topologically based on parent relationships."""
    result: list[dict[str, Any]] = []
    seen: set[str] = set()

    def visit(name: str) -> None:
        if name in seen:
            return
        seen.add(name)
        entry = next((e for e in spec if e["name"] == name), None)
        if entry and entry.get("parent"):
            parent_entry = next((e for e in spec if e["name"] == entry["parent"]), None)
            if parent_entry:
                visit(parent_entry["name"])
        if entry:
            result.append(entry)

    for entry in spec:
        visit(entry["name"])

    return result


def main() -> None:
    """Run the prepare execute step for split workflow."""
    import yaml

    args = _parse_args()

    spec: Any = json.loads(args.spec)
    # Handle _data wrapper if present (arrays get wrapped by workflow executor)
    if isinstance(spec, dict) and "_data" in spec:
        spec = spec["_data"]

    # Archive spec
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    archive_dir = Path.home() / ".sase" / "splits"
    archive_dir.mkdir(parents=True, exist_ok=True)
    archive_path = archive_dir / f"{args.cl_name}-{timestamp}.yml"
    with open(archive_path, "w") as f:
        yaml.dump(spec, f)

    # Topological sort
    sorted_spec = _topological_sort(spec)

    # Format markdown
    md_lines = []
    order_lines = []
    for i, entry in enumerate(sorted_spec):
        parent_suffix = f" (parent: {entry['parent']})" if entry.get("parent") else ""
        md_lines.append(f"- **{entry['name']}**: {entry['description']}{parent_suffix}")
        order_lines.append(f"{i + 1}. {entry['name']}{parent_suffix}")

    # Navigate to parent (suppress output to preserve JSON)
    subprocess.run(
        ["bb_hg_clean", f"{args.cl_name}-split-parent"],
        capture_output=True,
        check=True,
    )
    subprocess.run(
        ["bb_hg_update", args.default_parent],
        capture_output=True,
        check=True,
    )

    # Output as JSON (parser handles this correctly for multiline values)
    print(
        json.dumps(
            {
                "spec_markdown": "\n".join(md_lines),
                "processing_order": "\n".join(order_lines),
                "archive_path": str(archive_path).replace(str(Path.home()), "~"),
            }
        )
    )


if __name__ == "__main__":
    main()
