# Agentura MCP add-on for FreeCAD -- installer for version 1.0.0
#
# Paste this one line into FreeCAD's Python console (View > Panels > Python console):
#
#   import urllib.request as u; exec(u.urlopen(u.Request("https://agentura.ro/downloads/freecad/install.py", headers={"User-Agent": "FreeCAD"})).read())
#
# or run this file headless:  freecadcmd install.py
#
# It downloads AgenturaMCP-1.0.0.zip, checks its SHA-256, unpacks it into a
# temporary folder inside FreeCAD's Mod folder, checks the layout, and only
# then swaps it in as <FreeCAD user data>/Mod/AgenturaMCP. If any check fails,
# an existing add-on is left exactly as it was.
#
# Everything lives inside one function: pasted into the console, this adds
# only the name _agentura_mcp_install (call it again to retry).
#
# Generated by scripts/package-freecad-addon.sh from
# freecad-addon/installer/install.py.in -- edit the template, not this file.


def _agentura_mcp_install():
    import hashlib
    import importlib
    import io
    import os
    import shutil
    import ssl
    import stat
    import sys
    import tempfile
    import urllib.request
    import zipfile

    version = "1.0.0"
    zip_url = "https://agentura.ro/downloads/freecad/AgenturaMCP-1.0.0.zip"
    expected_sha256 = "89efbbf20de3734548dc36ef997494710a17e3c63cea041f89c77f97d92abd78"
    page_url = zip_url.rsplit("/", 1)[0] + "/"
    folder = "AgenturaMCP"
    package = "agentura_mcp"
    max_download = 32 * 1024 * 1024
    max_unpacked = 128 * 1024 * 1024
    max_entries = 5000
    user_agent = "FreeCAD AgenturaMCP-installer/" + version

    class Abort(Exception):
        """A handled failure: the message is shown as-is."""

    where = {"mod_dir": None}

    def say(message):
        print("Agentura MCP: " + message)

    def manual_hint():
        return ("To install by hand, download " + zip_url + ", unzip it into "
                + (where["mod_dir"] or "FreeCAD's Mod folder")
                + " and restart FreeCAD (see " + page_url + ").")

    # -- download ---------------------------------------------------------

    def download(context=None):
        request = urllib.request.Request(zip_url, headers={"User-Agent": user_agent})
        with urllib.request.urlopen(request, timeout=60, context=context) as response:
            data = response.read(max_download + 1)
        if len(data) > max_download:
            raise Abort("the download is larger than expected; nothing was changed.")
        return data

    def certificate_problem(error):
        reason = getattr(error, "reason", error)
        return (isinstance(reason, ssl.SSLCertVerificationError)
                or "CERTIFICATE_VERIFY_FAILED" in str(reason))

    def fetch():
        say("downloading " + zip_url)
        try:
            return download()
        except Abort:
            raise
        except Exception as error:
            if not certificate_problem(error):
                raise Abort("could not download the add-on (%s). Nothing was changed. %s"
                            % (error, manual_hint()))
        try:
            import certifi
        except ImportError:
            raise Abort("this Python could not verify the HTTPS certificate of the download "
                        "(CERTIFICATE_VERIFY_FAILED) and the certifi package is not available. "
                        "Nothing was changed. " + manual_hint())
        say("the system certificates were rejected; retrying with certifi's certificates")
        try:
            return download(ssl.create_default_context(cafile=certifi.where()))
        except Abort:
            raise
        except Exception as error:
            raise Abort("could not download the add-on (%s). Nothing was changed. %s"
                        % (error, manual_hint()))

    # -- unpack into a staging folder ---------------------------------------

    def unsafe(name):
        return Abort("the download contains an unsafe entry (%r); nothing was changed." % (name,))

    def unpack(data, staging):
        try:
            archive = zipfile.ZipFile(io.BytesIO(data))
        except zipfile.BadZipFile:
            raise Abort("the download is not a valid zip file; nothing was changed.")
        with archive:
            infos = archive.infolist()
            if not infos or len(infos) > max_entries:
                raise Abort("the download does not look like the add-on; nothing was changed.")
            total = 0
            # Check EVERY entry before writing anything.
            for info in infos:
                name = info.filename
                parts = name.rstrip("/").split("/")
                if (not name or "\\" in name or "\x00" in name or ":" in name
                        or name.startswith("/") or parts[0] != folder
                        or any(part in ("", ".", "..") for part in parts)
                        or stat.S_ISLNK(info.external_attr >> 16)):
                    raise unsafe(name)
                total += info.file_size
            if total > max_unpacked:
                raise Abort("the download unpacks to more than expected; nothing was changed.")
            root = os.path.realpath(staging)
            for info in infos:
                path = os.path.realpath(os.path.join(root, *info.filename.rstrip("/").split("/")))
                if not path.startswith(root + os.sep):
                    raise unsafe(info.filename)
                if info.is_dir():
                    os.makedirs(path, exist_ok=True)
                    continue
                os.makedirs(os.path.dirname(path), exist_ok=True)
                with archive.open(info) as source, open(path, "wb") as sink:
                    shutil.copyfileobj(source, sink)
        new_dir = os.path.join(staging, folder)
        for required in ("package.xml", package + "/__init__.py"):
            if not os.path.isfile(os.path.join(new_dir, *required.split("/"))):
                raise Abort("the download has no %s/%s; nothing was changed." % (folder, required))
        return new_dir

    # -- install ------------------------------------------------------------

    def same_path(a, b):
        return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))

    staging = None
    keep_staging = False
    try:
        try:
            import FreeCAD
        except ImportError:
            raise Abort("run this inside FreeCAD (View > Panels > Python console), "
                        "not in a plain Python.")
        gui = bool(getattr(FreeCAD, "GuiUp", False))
        mod_dir = where["mod_dir"] = os.path.join(FreeCAD.getUserAppDataDir(), "Mod")
        target = os.path.join(mod_dir, folder)
        say("installing version %s into %s" % (version, target))

        data = fetch()
        digest = hashlib.sha256(data).hexdigest()
        if digest != expected_sha256.lower():
            raise Abort("checksum mismatch (expected %s, got %s): the download was damaged "
                        "or altered. Nothing was changed." % (expected_sha256, digest))
        say("checksum OK")

        if os.path.islink(target):
            raise Abort(target + " is a link (a development checkout?). Remove the link "
                        "first; nothing was changed.")
        os.makedirs(mod_dir, exist_ok=True)
        staging = tempfile.mkdtemp(prefix=".AgenturaMCP-install-", dir=mod_dir)
        new_dir = unpack(data, staging)

        # Stop a running copy only now that the new files are known good.
        old = sys.modules.get(package)
        was_running = False
        if old is not None:
            try:
                was_running = bool(old.status().get("running"))
            except Exception:
                pass
            try:
                old.stop()
                if was_running:
                    say("stopped the running server")
            except Exception as error:
                say("could not stop the old server cleanly (%s); continuing" % (error,))

        upgrading = os.path.lexists(target)
        backup = os.path.join(staging, "previous")
        moved_aside = False
        try:
            if upgrading:
                os.rename(target, backup)
                moved_aside = True
            os.rename(new_dir, target)
        except Exception as error:
            if moved_aside:
                try:
                    os.rename(backup, target)
                except Exception:
                    keep_staging = True
                    raise Abort("could not replace %s (%s) nor put the previous add-on back; "
                                "it is in %s." % (target, error, backup))
            if old is not None and was_running and gui:
                try:
                    old.start()
                except Exception:
                    pass
            raise Abort("could not replace %s (%s); the previous add-on was left in place. "
                        "Close any program that has files from that folder open and try "
                        "again." % (target, error))

        for name in [n for n in list(sys.modules) if n == package or n.startswith(package + ".")]:
            del sys.modules[name]
        importlib.invalidate_caches()
        if not any(isinstance(p, str) and p and same_path(p, target) for p in sys.path):
            sys.path.insert(0, target)
        say("installed version %s" % version)

        try:
            fresh = importlib.import_module(package)
        except Exception as error:
            say("the add-on is installed but failed to load (%s: %s). Restart FreeCAD; if "
                "that does not help, see %s" % (type(error).__name__, error, page_url))
            return False
        loaded_from = os.path.dirname(os.path.dirname(os.path.abspath(fresh.__file__)))
        if not same_path(loaded_from, target):
            say("warning: Python loaded another copy of the add-on from %s; remove that copy "
                "so this one is used." % loaded_from)

        if gui:
            try:
                fresh.start()
            except Exception as error:
                say("the server did not start: %s" % (error,))
            try:
                status = fresh.status()
            except Exception as error:
                status = {"running": False, "error": str(error)}
            if status.get("running"):
                say("server running at %s (add-on %s)" % (status.get("url"), status.get("version")))
            else:
                say("server not running: %s" % (status.get("error") or "unknown reason"))
            say("status: %r" % (status,))
            if upgrading:
                say("restart FreeCAD when convenient to reload the Tools > Agentura MCP menu.")
            else:
                say("restart FreeCAD once to get the Tools > Agentura MCP menu.")
        else:
            say("this FreeCAD has no GUI, so the server was not started. Start it with:")
            print('    freecadcmd -c "import agentura_mcp; agentura_mcp.serve_forever()"')
        return True
    except Abort as error:
        say(str(error))
        return False
    except Exception as error:
        say("install failed (%s: %s). %s" % (type(error).__name__, error, manual_hint()))
        return False
    finally:
        if staging and not keep_staging:
            shutil.rmtree(staging, ignore_errors=True)


_agentura_mcp_install()
