#!/usr/bin/env python3
"""
backup_map.py — Manually trigger map save-as via the map_manager service.

Usage:
    ros2 run saltybot_mapping backup_map -- --name garden_session1
    ros2 run saltybot_mapping backup_map -- --name garden_session1 --overwrite
    ros2 run saltybot_mapping backup_map --  # auto-timestamped name
"""

import argparse
import sys
import rclpy
from rclpy.node import Node
from saltybot_mapping.srv import SaveMap, ListMaps


class BackupCLI(Node):
    def __init__(self):
        super().__init__('backup_map_cli')
        self._save_client = self.create_client(SaveMap,   '/mapping/maps/save_as')
        self._list_client = self.create_client(ListMaps,  '/mapping/maps/list')

    def save(self, name: str, overwrite: bool) -> bool:
        if not self._save_client.wait_for_service(timeout_sec=5.0):
            print('[ERROR] /mapping/maps/save_as service not available')
            return False
        req = SaveMap.Request()
        req.map_name  = name
        req.overwrite = overwrite
        fut = self._save_client.call_async(req)
        rclpy.spin_until_future_complete(self, fut, timeout_sec=30.0)
        resp = fut.result()
        if resp and resp.success:
            print(f'[OK] {resp.message}')
            return True
        print(f'[FAIL] {resp.message if resp else "No response"}')
        return False

    def list_maps(self) -> None:
        if not self._list_client.wait_for_service(timeout_sec=5.0):
            print('[ERROR] /mapping/maps/list service not available')
            return
        fut = self._list_client.call_async(ListMaps.Request())
        rclpy.spin_until_future_complete(self, fut, timeout_sec=10.0)
        resp = fut.result()
        if resp:
            print(f'Saved maps ({resp.count}):')
            for name, path, size, mtime in zip(
                    resp.map_names, resp.map_paths,
                    resp.sizes_bytes, resp.modified_times):
                print(f'  {name:<30} {size // 1024:>6} KB  {mtime}')


def main():
    parser = argparse.ArgumentParser(description='Backup current RTAB-Map database')
    parser.add_argument('--name',      default='', help='Map name (default: auto timestamp)')
    parser.add_argument('--overwrite', action='store_true', help='Overwrite existing map with same name')
    parser.add_argument('--list',      action='store_true', help='List saved maps and exit')
    args, ros_args = parser.parse_known_args()

    rclpy.init(args=ros_args)
    node = BackupCLI()
    if args.list:
        node.list_maps()
        ok = True
    else:
        ok = node.save(args.name, args.overwrite)
    node.destroy_node()
    rclpy.shutdown()
    sys.exit(0 if ok else 1)


if __name__ == '__main__':
    main()
