# tenkana, a spider that jumps from the checkpoints of your TeX document.
# Copyright © 2026 निरंजन (Niranjan)
#
# tenkana is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# tenkana is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with tenkana.  If not, see <https://www.gnu.org/licenses/>.
#
# tenkana was written by Claude, a large language model (LLM) made by
# Anthropic.  Courts are divided on whether material generated by an LLM can be
# protected by copyright.  Should it be found that the copyright claimant
# cannot hold copyright in any part of tenkana, that part is in the public
# domain.  Wherever copyright does hold, tenkana is distributed under the terms
# of the GNU General Public License, version 3 or (at your option) any later
# version, as stated above.


"""__main__.py of tenkana.pyz, the single-file `tenkana' (build.sh puts it
there, with KEY set to a hash of the files in the zip).

Python cannot keep the compiled form (bytecode) of modules it imports from a
zip file, so it would compile tenkana's source again on every run.  On first
use, tenkana unpacks its own files into $XDG_CACHE_HOME/tenkana/py-<hash>/
(by default ~/.cache/tenkana/py-<hash>/), where Python keeps the bytecode
as usual, and runs from there.  The hash changes with every change of
tenkana, so an unpacked copy is never out of date.  Without a usable cache,
tenkana runs from the zip itself, as before.
"""

import os
import sys

KEY = "@KEY@"


def cached():
    """The folder of the unpacked copy (made now if needed), or None."""
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(
        os.path.expanduser("~"), ".cache"
    )
    top = os.path.join(base, "tenkana")
    d = os.path.join(top, "py-" + KEY)
    try:
        st = os.stat(d)
        # only our own copy, which nobody else can change, is code to run
        if st.st_uid == os.getuid() and not st.st_mode & 0o022:
            os.utime(d)  # in use: see the clean-up below
            return d
        return None
    except OSError:
        pass
    try:
        import shutil
        import tempfile
        import time
        import zipfile

        os.makedirs(top, mode=0o700, exist_ok=True)
        tmp = tempfile.mkdtemp(prefix="py-new-", dir=top)
        with zipfile.ZipFile(os.path.dirname(os.path.abspath(__file__))) as z:
            for name in z.namelist():
                if name.startswith("tenkana/"):
                    z.extract(name, tmp)
        try:
            os.rename(tmp, d)  # complete or not at all
        except OSError:  # another tenkana was first
            shutil.rmtree(tmp, ignore_errors=True)
        # copies of older versions of tenkana, unused for a day
        for n in os.listdir(top):
            p = os.path.join(top, n)
            if n.startswith("py-") and p != d:
                if time.time() - os.stat(p).st_mtime > 86400:
                    shutil.rmtree(p, ignore_errors=True)
        return d if os.path.isdir(d) else None
    except Exception:  # an unusable cache: run from the zip
        return None


d = cached()
if d:
    sys.path.insert(0, d)
    try:
        from tenkana.cli import entry
    except ImportError:  # a damaged copy: the zip has the same files
        sys.path.remove(d)
        for m in [m for m in sys.modules if m.split(".")[0] == "tenkana"]:
            del sys.modules[m]
        from tenkana.cli import entry
else:
    from tenkana.cli import entry
entry()
