"""
Example: Capture a snapshot from an LT device input

This example demonstrates how to:
    1. Connect to a given input source on an LT device.
    2. Verify that the source has a locked video signal.
    3. Create a worker to capture a snapshot in JPEG format.
    4. Save the snapshot to the current working directory.
    5. Print the file name, resolution, and file size.

Usage:
    still_capture.exe -source <sourceURL>

Arguments:
    -source, -s   URL of a valid LT device input, for example:
                      lt310:/0/hdmi-in/0
                      lt310:/0/sdi-in/1

Note:
    This code is intended for demonstration purposes. For production use,
    ensure proper error handling and resource cleanup.

Requirements: pywin32

© 2025 Enciris Technologies. All rights reserved.
"""

import argparse
import os

if __package__:
    from ... import lt
else:
    import sys
    sys.path.append("../..")
    import lt


# Command line arguments
def parse_args():
    class MyParser(argparse.ArgumentParser):
        def error(self, message):
            self.print_help()
            self.exit(2, f"\nError: {message}\n")

    parser = MyParser(
        description=(
            "This example verifies that the selected input source is active,\n"
            "captures a snapshot as a JPEG image, and prints its file information."
        ),
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=False
    )

    group = parser.add_argument_group("Arguments")
    group.add_argument(
        "-source", "-s",
        required=True,
        metavar="URL",
        help=(
            "URL of a valid LT device input (e.g. lt310:/0/hdmi-in/0)\n"
        )
    )

    return parser.parse_args()


def main():
    args = parse_args()
    sourceURL = args.source

    # Create LT client
    client = lt.Client()

    # -------------------------------------------------------------------------
    # Check if input selected is active
    # -------------------------------------------------------------------------
    try:
        input = client.Get(sourceURL)
        if input['video']['signal'] != 'locked':
            raise RuntimeError("input video source has no signal")
    except lt.SDKError as e:
        raise RuntimeError(f"error connecting to {sourceURL}: {e}") from e

    # -------------------------------------------------------------------------
    # Take a snapshot of the selected input
    # -------------------------------------------------------------------------
    # Create worker to capture the image
    workerURL = ""
    try:
        client.Post(sourceURL+"/file", lt.JSON({'media': "image/jpeg", 'location': os.getcwd()}))
    except lt.RedirectError as e:
        workerURL = e.location
    except lt.SDKError as e:
        raise RuntimeError("server did not return a redirect")

    # Fetch worker response
    try:
        worker = client.Get(workerURL)
    except lt.SDKError as e:
        raise RuntimeError(f"error fetching worker data from {workerURL}: {e}") from e

    # Packet data
    if len(worker['packets']) == 0:
        exit("packet not found")
    packet = worker['packets'][0]

    # Packet metadata
    meta = packet['meta']

    # Print file information
    print('{:s} {:s} {:d}x{:d} {:d} bytes'.format(sourceURL, worker['name'], meta['size'][0], meta['size'][1], worker['length']))

if __name__ == "__main__":
    main()
