"""
Archive extractor module for NovinAcc accounting software.
"""

import logging
import os
from pathlib import Path
import shutil
from typing import Optional
import zipfile

from module.config import InstallerConfig, detect_target_drive

logger = logging.getLogger("acc_installer")


def extract_acc_archive(config: Optional[InstallerConfig] = None, 
                        archive_name: str = "NovinAcc.zip") -> Path:
    """
    Locates NovinAcc archive in NovinSoft, moves it to NovinAcc, and extracts its contents.
    """
    if config is None:
        config = InstallerConfig()

    source_zip = config.soft_dir / archive_name
    target_zip = config.acc_dir / archive_name

    config.ensure_directories()

    if config.dry_run:
        print(f"  [DRY-RUN] Would locate {archive_name} in {config.soft_dir}, move to {config.acc_dir} and extract.")
        return config.acc_dir

    # Check if archive exists in soft_dir or already in acc_dir
    archive_to_extract = None
    if source_zip.exists():
        archive_to_extract = source_zip
    elif target_zip.exists():
        archive_to_extract = target_zip
    else:
        raise FileNotFoundError(
            f"Archive '{archive_name}' was not found in either {config.soft_dir} or {config.acc_dir}!"
        )

    # Move archive to target NovinAcc directory if not already there
    if archive_to_extract != target_zip:
        print(f"[+] Moving {archive_name} to NovinAcc directory...")
        shutil.move(str(source_zip), str(target_zip))
        print("  [+] Zip archive moved successfully.")

    # Extract archive
    print(f"[+] Extracting {archive_name} into {config.acc_dir} ...")
    with zipfile.ZipFile(target_zip, 'r') as zip_ref:
        zip_ref.extractall(config.acc_dir)
    print("  [+] All archive files extracted successfully.")

    # Remove temporary zip file
    if target_zip.exists():
        target_zip.unlink()
        print("  [+] Temporary zip archive cleaned up.")

    return config.acc_dir


if __name__ == "__main__":
    import sys
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    print("[*] Running NovinAcc archive extractor standalone ...")
    try:
        cfg = InstallerConfig(target_drive=detect_target_drive())
        extract_acc_archive(cfg)
        print("[+] NovinAcc extraction completed successfully.")
    except Exception as e:
        print(f"[-] Error: {e}", file=sys.stderr)
        sys.exit(1)
