import logging
import argparse
from .backup import Backup
from . import __version__


def build_parser():
    parser = argparse.ArgumentParser(description="iOS Backup Browser")
    parser.add_argument(
        "-V", "--version",
        action="version",
        version=f"ios_backup {__version__}",
        help="Show the version number and exit"
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    parser_export = subparsers.add_parser("export", help="Export files from iOS backup")
    parser_export.add_argument("backup_path", type=str, help="Path to the iOS backup directory")
    parser_export.add_argument("output_path", type=str, help="Path to export files")
    parser_export.add_argument("--domain", type=str, help="Filter by domain prefix", metavar="prefix")
    parser_export.add_argument("--namespace", type=str, help="Filter by namespace", metavar="prefix")
    parser_export.add_argument("--path", type=str, help="Filter by device path prefix", metavar="prefix")
    parser_export.add_argument("--ignore-missing", action="store_true", help="Ignore missing files during export")
    parser_export.add_argument("--restore-dates", action="store_true", help="Restore modified dates")
    parser_export.add_argument("--restore-symlinks", action="store_true", help="Restore symlbolic links")
    parser_export.set_defaults(func=handle_export)

    return parser


def handle_export(args):
    if not args.backup_path or not args.output_path:
        logging.error("Both backup_path and output_path are required for export command.")
        exit(1)
    
    export(
        args.backup_path,
        args.output_path,
        args.domain or "",
        args.namespace or "",
        args.path or "",
        args.ignore_missing,
        args.restore_dates,
        args.restore_symlinks,
    )
    
def export(
        backup_path: str,
        output_path: str,
        domain_prefix: str,
        namespace_prefix: str,
        path_prefix: str,
        ignore_missing: bool = True,
        restore_modified_dates: bool = False,
        restore_symlinks: bool = False,
    ) -> None:
    backup = Backup(backup_path)
    content = backup.get_content(domain_prefix, namespace_prefix,
                                 path_prefix, parse_metadata=restore_modified_dates)
    content_count = backup.get_content_count(domain_prefix, namespace_prefix, path_prefix)
    backup.export(content, output_path, ignore_missing, restore_modified_dates, restore_symlinks, content_count)
    backup.close()
    logging.info(f"{content_count} entries processed")


def handle_cli():
    parser = build_parser()
    try:
        args = parser.parse_args()
    except Exception:
        parser.print_help()
        exit(1)
    
    args.func(args)


def main():
    try:
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
        handle_cli()
    except Exception as e:    
        logging.error(f"An error occurred: {e}", exc_info=True)
        exit(1)


if __name__ == "__main__":
    main()
