#!/usr/bin/env python3
"""
Build Jira description ADF (with clickable links) from a list of {title, url}.
Reads JSON array from stdin or from file. Writes ADF JSON to stdout or to --output.

Input JSON format: [{"title": "Page 1", "url": "https://..."}, ...]
"""
import argparse
import json
import sys


def build_adf(pages, intro_text=None):
    """Build ADF doc with optional intro paragraph and bullet list of links."""
    content = []
    if intro_text:
        content.append({
            "type": "paragraph",
            "content": [{"type": "text", "text": intro_text}]
        })
    if pages:
        list_items = []
        for p in pages:
            title = (p.get("title") or p.get("name") or "Link").strip()
            url = (p.get("url") or p.get("href") or "").strip()
            if not url:
                continue
            list_items.append({
                "type": "listItem",
                "content": [{
                    "type": "paragraph",
                    "content": [{
                        "type": "text",
                        "text": title,
                        "marks": [{"type": "link", "attrs": {"href": url}}]
                    }]
                }]
            })
        if list_items:
            content.append({"type": "bulletList", "content": list_items})
    return {"type": "doc", "version": 1, "content": content or [{"type": "paragraph", "content": []}]}


def main():
    parser = argparse.ArgumentParser(description="Build Jira ADF from list of pages (title, url)")
    parser.add_argument("input", nargs="?", default="-", help="Input JSON file or - for stdin")
    parser.add_argument("--output", "-o", default="-", help="Output ADF JSON file or - for stdout")
    parser.add_argument("--intro", default="Documentación / páginas de referencia en Notion:", help="Intro paragraph text")
    args = parser.parse_args()
    if args.input == "-":
        data = json.load(sys.stdin)
    else:
        with open(args.input, "r", encoding="utf-8") as f:
            data = json.load(f)
    if not isinstance(data, list):
        data = data.get("pages", data.get("results", [data]))
    adf = build_adf(data, intro_text=args.intro or None)
    out = json.dumps(adf, ensure_ascii=False, indent=2)
    if args.output == "-":
        print(out)
    else:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(out)


if __name__ == "__main__":
    main()
