"""
CLI: signalwire-slides

Commands:
    signalwire-slides list                # show all 29 layouts with descriptions
    signalwire-slides show L04            # print source code of a layout
    signalwire-slides show content        # same, by name
    signalwire-slides build               # build reference deck (both themes)
    signalwire-slides build --theme dark  # dark only
    signalwire-slides build -o /tmp       # custom output dir
"""

import argparse
import inspect
import os
import sys


def cmd_list(args):
    """List all available layouts."""
    from . import LAYOUT_INFO
    print(f"\nSignalWire Slide Builder — {len(LAYOUT_INFO)} layouts\n")
    print(f"  {'ID':<6} {'Name':<22} Description")
    print(f"  {'—'*5:<6} {'—'*20:<22} {'—'*50}")
    for info in LAYOUT_INFO:
        print(f"  {info['id']:<6} {info['name']:<22} {info['desc']}")
    print(f"\nUsage:")
    print(f"  signalwire-slides show L04          # view layout source code")
    print(f"  signalwire-slides show content       # same, by name")
    print(f"  signalwire-slides build              # build reference deck\n")


def cmd_show(args):
    """Show the source code of a layout."""
    from . import CATALOG, LAYOUT_INFO
    key = args.layout
    # Try direct catalog lookup
    fn = CATALOG.get(key) or CATALOG.get(key.upper()) or CATALOG.get(key.lower())
    if not fn:
        # Try partial match on name
        for info in LAYOUT_INFO:
            if key.lower() in info["name"].lower() or key.lower() in info["id"].lower():
                fn = info["fn"]
                break
    if not fn:
        print(f"Unknown layout '{key}'. Run: signalwire-slides list")
        sys.exit(1)
    # Find the info entry
    info = next((i for i in LAYOUT_INFO if i["fn"] == fn), None)
    if info:
        print(f"\n# {info['id']}: {info['name']}")
        print(f"# {info['desc']}\n")
    print(inspect.getsource(info["module"] if info else fn))


def cmd_build(args):
    """Build reference deck."""
    from pptx import Presentation
    from .core import (
        SW, SH, GRAD, LIGHT,
        LOGO_WHITE_SVG, LOGO_BLACK_SVG, svg_to_png,
    )
    from . import ALL_LAYOUTS, RESOURCE_LAYOUTS, LAYOUT_NAMES
    from .L15_closing import L15_closing
    from .L17_blank_dark import L17_blank_dark
    from .L18_blank_light import L18_blank_light

    def build_deck(theme_config, logo_png, logo_white_png, suffix, output_dir):
        prs = Presentation()
        prs.slide_width = SW; prs.slide_height = SH
        bk = prs.slide_layouts[6]
        for fn in ALL_LAYOUTS:
            if fn == L15_closing:
                fn(prs, bk, theme_config, logo_png, logo_white=logo_white_png)
            else:
                fn(prs, bk, theme_config, logo_png)
        for fn in RESOURCE_LAYOUTS:
            fn(prs, bk, theme_config, logo_png)
        if theme_config["is_gradient"]:
            L17_blank_dark(prs, bk, theme_config, logo_png)
        else:
            L18_blank_light(prs, bk, theme_config, logo_png)
        out = os.path.join(output_dir, f"SignalWire_Template_{suffix}.pptx")
        prs.save(out)
        return out, len(prs.slides)

    lw = svg_to_png(LOGO_WHITE_SVG, width=800)
    lb = svg_to_png(LOGO_BLACK_SVG, width=800)

    builds = []
    if args.theme in ("dark", "both"):
        builds.append((GRAD, lw, lw, "Dark", "DARK GRADIENT"))
    if args.theme in ("light", "both"):
        builds.append((LIGHT, lb, lw, "Light", "LIGHT"))

    for theme, logo, logo_w, suffix, label in builds:
        out, count = build_deck(theme, logo, logo_w, suffix, args.output_dir)
        print(f"\n{label}: {out}")
        print(f"  {count} slides:")
        for i, n in enumerate(LAYOUT_NAMES):
            print(f"    {i+1:2}. {n}")


def main():
    parser = argparse.ArgumentParser(
        prog="signalwire-slides",
        description="SignalWire branded slide deck builder"
    )
    sub = parser.add_subparsers(dest="command")

    # list
    sub.add_parser("list", help="Show all available layouts")

    # show
    show_p = sub.add_parser("show", help="View source code of a layout")
    show_p.add_argument("layout", help="Layout ID (L04) or name (content)")

    # build
    build_p = sub.add_parser("build", help="Build reference deck")
    build_p.add_argument("--theme", choices=["dark", "light", "both"], default="both")
    build_p.add_argument("-o", "--output-dir", default=".")

    args = parser.parse_args()

    if args.command == "list":
        cmd_list(args)
    elif args.command == "show":
        cmd_show(args)
    elif args.command == "build":
        cmd_build(args)
    else:
        # Default: show help
        parser.print_help()
        print("\nQuick start:")
        print("  signalwire-slides list     # see all layouts")
        print("  signalwire-slides build    # build reference deck")


if __name__ == "__main__":
    main()
