#!/usr/bin/env python3
"""Set a bead's design field from a file.

Works around a clap CLI parsing bug where content starting with '---'
(YAML frontmatter) or containing '--' is misinterpreted as CLI flags.

Usage:
    scripts/br-set-design <bead-id> <file-path>

Examples:
    scripts/br-set-design mcp-24s9 docs/plans/2026-02-23-fix-enforce-https-only-protocol-plan.md
    scripts/br-set-design mcp-1v4u docs/plans/2026-02-23-fix-httpRequest-header-redaction-plan.md
"""

import subprocess
import sys


def strip_frontmatter(content: str) -> str:
    """Remove YAML frontmatter (--- delimited block at start of file)."""
    if not content.startswith("---"):
        return content
    try:
        end = content.index("---", 3)
        return content[end + 3 :].lstrip("\n")
    except ValueError:
        return content


def main():
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} <bead-id> <file-path>", file=sys.stderr)
        sys.exit(1)

    bead_id = sys.argv[1]
    file_path = sys.argv[2]

    with open(file_path, "r") as f:
        content = f.read()

    content = strip_frontmatter(content)

    result = subprocess.run(
        ["br", "update", bead_id, "--design", content],
        capture_output=True,
        text=True,
    )

    if result.stdout:
        print(result.stdout, end="")
    if result.stderr:
        print(result.stderr, end="", file=sys.stderr)

    sys.exit(result.returncode)


if __name__ == "__main__":
    main()
