#! /usr/bin/env python3
import argparse
import sys
import logging
import subprocess
from datetime import datetime

logger = logging.getLogger(__name__)

def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(prog='blink-check', description='Check on a running blink-fetch cron task')
    ap.add_argument("hostname", help="[user@]hostname[:port] for SSH")
    ap.add_argument("--image-dir", help="Remote directory containing fetched images", default="/home/ewpratten/Pictures/blink")
    ap.add_argument("--camera-id", help="Camera ID", default="155295")
    ap.add_argument("--show-latest", "--show", "-s", help="Download and display the latest image (if possible)", action="store_true")
    ap.add_argument('-v', '--verbose', help='Enable verbose logging', action='store_true')
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format='%(levelname)s:	%(message)s',
    )
    
    # List files in image directory
    logger.info(f"Listing files in: {args.hostname}:{args.image_dir}")
    result = subprocess.run(
        [
            "ssh",
            args.hostname,
            "ls",
            "-1",
            args.image_dir,
        ],
        capture_output=True,
        text=True,
    )
    
    # Check for errors
    if result.returncode != 0:
        logger.error(f"Failed to list files in: {args.hostname}:{args.image_dir}")
        logger.error(result.stderr)
        return 1
    
    # Find all frames
    frames = result.stdout.splitlines()
    frames = [frame for frame in frames if frame.startswith(f"camera_{args.camera_id}.")]
    frames = sorted(frames)
    logger.info(f"Found {len(frames)} frames")
    if len(frames) > 0:
        oldest_frame_time = datetime.strptime(frames[0].split('.')[1], "%Y%m%d_%H%M%S")
        newest_frame_time = datetime.strptime(frames[-1].split('.')[1], "%Y%m%d_%H%M%S")
        logger.info(f"Oldest frame is from: {oldest_frame_time}")
        logger.info(f"Newest frame is from: {newest_frame_time}")
        
    # Download and display the latest image
    if args.show_latest:
        if len(frames) > 0:
            latest_frame = frames[-1]
            logger.info(f"Downloading latest frame: {latest_frame}")
            result = subprocess.run(
                [
                    "scp",
                    f"{args.hostname}:{args.image_dir}/{latest_frame}",
                    "/tmp/blink-latest.jpg",
                ],
                capture_output=True,
                text=True,
            )
            
            # Check for errors
            if result.returncode != 0:
                logger.error(f"Failed to download latest frame: {latest_frame}")
                logger.error(result.stderr)
                return 1
            
            # Display image
            logger.info(f"Displaying latest frame: {latest_frame}")
            result = subprocess.run(
                [
                    "xdg-open",
                    "/tmp/blink-latest.jpg",
                ],
                capture_output=True,
                text=True,
            )
            
            # Check for errors
            if result.returncode != 0:
                logger.error(f"Failed to display latest frame: {latest_frame}")
                logger.error(result.stderr)
                return 1
        else:
            logger.info(f"No frames to display")
    

    return 0

if __name__ == "__main__":
    sys.exit(main())