#!/usr/bin/env apython3
"""
Split Jira backlog report into individual LLD documents.

For each ticket in the "## Detailed Breakdown" section of a Jira report:
  - Creates a standalone LLD file in docs/phase-2/llds/
  - Replaces the full content block in the report with a stub + link

Usage:
    python scripts/split_jira_report_to_llds.py [path/to/report.md]

If no path is given, defaults to docs/reports/jira/20260315.md
"""

import re
import sys
from pathlib import Path

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_REPORT = REPO_ROOT / "docs" / "reports" / "jira" / "20260315.md"
LLD_DIR = REPO_ROOT / "docs" / "phase-2" / "llds"

# Relative path used *inside the report* when linking to a new LLD file
REPORT_TO_LLD_REL = "../../phase-2/llds"


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def slugify(text: str) -> str:
    """Convert a title string to a filename-safe lowercase slug."""
    text = text.lower()
    text = re.sub(r"[^a-z0-9\s-]", "", text)   # strip special chars
    text = re.sub(r"\s+", "-", text.strip())     # spaces → hyphens
    text = re.sub(r"-+", "-", text)              # collapse consecutive hyphens
    return text[:80]                             # cap at 80 chars


def parse_ticket_heading(block: str):
    """
    Return (key, jira_url, title) if the block starts with a DEB-XXX heading.
    Otherwise return None.
    """
    match = re.match(
        r"#+\s+\[(?P<key>DEB-\d+)\]\((?P<url>[^)]+)\):\s*(?P<title>.+)",
        block.lstrip(),
    )
    if not match:
        return None
    return match.group("key"), match.group("url"), match.group("title").strip()


def extract_one_liner(block: str) -> str:
    """
    Pull the first meaningful line of the description to use as a subtitle
    in the stub that remains in the report.
    """
    in_desc = False
    for line in block.splitlines():
        stripped = line.strip()
        if stripped == "**Description:**":
            in_desc = True
            continue
        if in_desc:
            if stripped.startswith("*No description"):
                return ""
            if stripped and not stripped.startswith("**") and not stripped.startswith("-"):
                return stripped[:200]
            if stripped.startswith("-"):
                return stripped.lstrip("- ").strip()[:200]
    return ""


def build_lld_content(
    key: str, jira_url: str, title: str, body: str, report_filename: str
) -> str:
    """Return the full content for the new standalone LLD file."""
    return (
        f"# {key}: {title}\n\n"
        f"> **Jira:** [{key}]({jira_url})  \n"
        f"> **Source Report:** [{report_filename}](../../../reports/jira/{report_filename})\n\n"
        f"{body.strip()}\n"
    )


def build_stub(
    key: str,
    jira_url: str,
    title: str,
    lld_filename: str,
    one_liner: str,
) -> str:
    """Return the compact stub that replaces the ticket block in the report."""
    subtitle = f"\n> {one_liner}" if one_liner else ""
    return (
        f"### [{key}]({jira_url}): {title}\n"
        f"{subtitle}\n\n"
        f"📄 **Full LLD:** [{lld_filename}]({REPORT_TO_LLD_REL}/{lld_filename})\n\n"
        f"---"
    )


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main(report_path: Path) -> None:
    LLD_DIR.mkdir(parents=True, exist_ok=True)

    text = report_path.read_text(encoding="utf-8")

    # ---- Split at the "## Detailed Breakdown" header ----------------------
    breakdown_marker = "\n## Detailed Breakdown\n"
    if breakdown_marker not in text:
        print("ERROR: Could not find '## Detailed Breakdown' section in report.")
        sys.exit(1)

    header_part, breakdown_part = text.split(breakdown_marker, 1)

    # ---- Split breakdown into per-ticket blocks ---------------------------
    # Blocks are separated by lines that contain only "---"
    raw_blocks = re.split(r"\n---\n", breakdown_part)

    new_blocks: list[str] = []
    created: list[str] = []
    skipped: list[str] = []

    for block in raw_blocks:
        block = block.strip()
        if not block:
            continue

        parsed = parse_ticket_heading(block)
        if not parsed:
            # Not a ticket block — preserve verbatim (e.g. trailing footer text)
            new_blocks.append(block)
            continue

        key, jira_url, title = parsed

        # Body = everything after the ### heading line
        heading_line_end = block.index("\n") + 1
        body = block[heading_line_end:].strip()

        # ---- Build LLD file -----------------------------------------------
        slug = slugify(f"{key}-{title}")
        lld_filename = f"{slug}.md"
        lld_path = LLD_DIR / lld_filename

        if lld_path.exists():
            skipped.append(lld_filename)
        else:
            lld_content = build_lld_content(
                key, jira_url, title, body, report_path.name
            )
            lld_path.write_text(lld_content, encoding="utf-8")
            created.append(lld_filename)

        # ---- Build stub for the report ------------------------------------
        one_liner = extract_one_liner(block)
        stub = build_stub(key, jira_url, title, lld_filename, one_liner)
        new_blocks.append(stub)

    # ---- Rebuild the report -----------------------------------------------
    new_breakdown = "\n\n".join(new_blocks)
    new_text = header_part + breakdown_marker + "\n" + new_breakdown + "\n"
    report_path.write_text(new_text, encoding="utf-8")

    # ---- Summary ----------------------------------------------------------
    for f in created:
        print(f"  CREATED : {LLD_DIR.relative_to(REPO_ROOT)}/{f}")
    for f in skipped:
        print(f"  SKIPPED : {LLD_DIR.relative_to(REPO_ROOT)}/{f}  (already exists)")

    print(
        f"\nDone — {len(created)} LLD files created, {len(skipped)} skipped.\n"
        f"Report updated: {report_path.relative_to(REPO_ROOT)}"
    )


if __name__ == "__main__":
    target = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_REPORT
    if not target.is_absolute():
        target = REPO_ROOT / target
    if not target.exists():
        print(f"ERROR: Report file not found: {target}")
        sys.exit(1)
    main(target)
