#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import shutil
import stat
from datetime import datetime
from pathlib import Path

PACKAGE_NAME = "affinity-sched"
PACKAGE_DIR = PACKAGE_NAME.replace("-", "_")


def _log(level: str, message: str, *, stream=None):
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[msboost][{ts}][{level}]: {message}", file=stream or sys.stdout)


def log_info(message: str):
    _log("INFO", message)


def log_warning(message: str):
    _log("WARNING", message, stream=sys.stderr)


def log_error(message: str):
    _log("ERROR", message, stream=sys.stderr)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--install-path", required=True, help="Specify the installation path")
    args = parser.parse_args()

    log_info(f"Starting uninstallation of {PACKAGE_NAME}")

    install_path = Path(args.install_path)

    target = install_path / "python" / "site-packages"
    removed = False
    for dist_info in sorted(target.glob(f"{PACKAGE_DIR}-*.dist-info")):
        record = dist_info / "RECORD"
        if record.exists():
            for line in record.read_text().splitlines():
                filepath = line.split(",")[0]
                full_path = target / filepath
                if full_path.exists():
                    full_path.unlink()
                    removed = True
        shutil.rmtree(dist_info, ignore_errors=True)
        removed = True
    pkg_dir = target / PACKAGE_DIR
    if pkg_dir.is_dir():
        shutil.rmtree(pkg_dir)
        removed = True
    if not removed:
        log_warning(f"Package {PACKAGE_NAME} not found in {target}")

    info_dir = install_path / "share" / "info" / "msboost"
    for f in ["version.info", "uninstall.sh"]:
        p = info_dir / f
        if p.exists():
            p.unlink()
    if info_dir.is_dir() and not any(info_dir.iterdir()):
        shutil.rmtree(info_dir)

    cann_uninstall = install_path / "cann_uninstall.sh"
    entry = 'uninstall_package "share/info/msboost"'
    if cann_uninstall.exists():
        lines = cann_uninstall.read_text().splitlines()
        if any(line.strip() == entry for line in lines):
            new_lines = [l for l in lines if l.strip() != entry]
            content = "\n".join(new_lines) + "\n" if new_lines else ""
            original_mode = cann_uninstall.stat().st_mode
            need_restore = not os.access(cann_uninstall, os.W_OK)
            if need_restore:
                cann_uninstall.chmod(original_mode | stat.S_IWUSR)
            try:
                cann_uninstall.write_text(content)
            finally:
                if need_restore:
                    try:
                        cann_uninstall.chmod(original_mode)
                    except PermissionError:
                        pass

    log_info("Uninstallation completed successfully")


if __name__ == "__main__":
    main()