#!/usr/bin/env python3
"""Install the manifest-verified skill and scheduler helpers using Python 3.10+."""

import argparse
import contextlib
import hashlib
import json
import os
import pathlib
import re
import shutil
import sys
import tempfile
import urllib.error
import urllib.request


packageName = "learn-from-reddit"
packageUrl = "https://www.demetriusmichael.com/posts/learn-from-reddit/package/"
maximumFileBytes = 2 * 1024 * 1024
maximumPackageBytes = 16 * 1024 * 1024
skillRoots = dict.fromkeys(("codex", "pi", "opencode", "gemini"), ".agents/skills")
skillRoots["claude"] = ".claude/skills"


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, connection, code, message, headers, newUrl):
        raise ValueError("Package downloads cannot follow redirects.")


def relativePath(value):
    if not isinstance(value, str) or not value or len(value) > 240:
        raise ValueError("Manifest contains an invalid relative path.")
    parts = value.split("/")
    if any(part in ("", ".", "..") or not re.fullmatch(r"[A-Za-z0-9_.-]+", part) for part in parts):
        raise ValueError("Manifest paths must be plain relative file paths.")
    return pathlib.PurePosixPath(value)


def readSource(source, relative):
    if source is not None:
        sourcePath = source.joinpath(*relativePath(relative).parts)
        sourcePath.resolve().relative_to(source)
        with sourcePath.open("rb") as stream:
            content = stream.read(maximumFileBytes + 1)
    else:
        request = urllib.request.Request(packageUrl + str(relativePath(relative)), headers={"User-Agent": "learn-from-reddit-installer/0.1"})
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as stream:
            content = stream.read(maximumFileBytes + 1)
    if len(content) > maximumFileBytes:
        raise ValueError("A package file exceeds the size limit.")
    return content


def readPackage(source):
    manifest = json.loads(readSource(source, "manifest.json"))
    if manifest.get("schemaVersion") != 1 or manifest.get("name") != packageName:
        raise ValueError("The package manifest is not supported.")
    if not isinstance(manifest.get("version"), str) or not re.fullmatch(r"\d+\.\d+\.\d+", manifest["version"]):
        raise ValueError("The package version must have three numeric components.")
    entries = manifest.get("files")
    if not isinstance(entries, list) or not 1 <= len(entries) <= 200:
        raise ValueError("The manifest must list between 1 and 200 files.")
    contents = {}
    for entry in entries:
        if not isinstance(entry, dict):
            raise ValueError("Invalid manifest file entry.")
        relative = str(relativePath(entry.get("path")))
        digest = entry.get("sha256", "")
        if relative == "manifest.json" or relative in contents or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
            raise ValueError("The manifest contains duplicate files or invalid hashes.")
        content = readSource(source, relative)
        if hashlib.sha256(content).hexdigest() != digest:
            raise ValueError(f"Checksum verification failed: {relative}")
        contents[relative] = content
        if sum(map(len, contents.values())) > maximumPackageBytes:
            raise ValueError("The package exceeds the total size limit.")
    required = {f"skills/{packageName}/SKILL.md", f"skills/{packageName}/scripts/feedback.py", "install.py", "monitor.py"}
    if not required.issubset(contents):
        raise ValueError("The manifest omits a required skill or helper file.")
    return manifest, contents


def containedPath(project, relative):
    target = project.joinpath(*relativePath(relative).parts)
    target.resolve().relative_to(project)
    for parent in (target, *target.parents):
        if parent == project:
            break
        if parent.is_symlink():
            raise ValueError("Installation paths cannot contain symlinks.")
    return target


@contextlib.contextmanager
def installLock(path):
    with path.open("a+b") as stream:
        if os.name == "nt":
            import msvcrt
            stream.seek(0)
            stream.write(b"0")
            stream.flush()
            stream.seek(0)
            msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
        else:
            import fcntl
            fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        yield


def verifyExisting(project, skillRoot, recordPath, isUpdate):
    directories = (containedPath(project, f"{skillRoot}/{packageName}"), containedPath(project, ".community-feedback/bin"))
    hasExisting = recordPath.exists() or any(directory.exists() for directory in directories)
    if not hasExisting:
        return
    if not isUpdate or not recordPath.is_file():
        raise ValueError("Existing files were left unchanged. Use --update only for an installation made by this installer.")
    record = json.loads(recordPath.read_text(encoding="utf-8"))
    if record.get("name") != packageName or record.get("skillRoot") != skillRoot or not isinstance(record.get("files"), dict):
        raise ValueError("The existing installation record does not match this skill location.")
    actual = set()
    for directory in directories:
        for path in directory.rglob("*"):
            if path.is_symlink():
                raise ValueError("The existing installation contains a symlink; no files were replaced.")
            if path.is_file():
                actual.add(path.relative_to(project).as_posix())
    if actual != set(record["files"]):
        raise ValueError("The installed file set changed; preserve those edits before updating.")
    for relative, digest in record["files"].items():
        current = containedPath(project, relative)
        if hashlib.sha256(current.read_bytes()).hexdigest() != digest:
            raise ValueError(f"A local file changed; no files were replaced: {relative}")


def installPackage(project, harness, manifest, contents, isUpdate):
    skillRoot = skillRoots[harness]
    control = containedPath(project, ".community-feedback")
    control.mkdir(mode=0o700, exist_ok=True)
    recordPath = containedPath(project, ".community-feedback/install.json")
    with installLock(containedPath(project, ".community-feedback/install.lock")):
        verifyExisting(project, skillRoot, recordPath, isUpdate)
        with tempfile.TemporaryDirectory(prefix=".install-", dir=control) as temporary:
            staging = pathlib.Path(temporary)
            stagedSkill = staging / "skill"
            stagedHelpers = staging / "bin"
            installedHashes = {}
            for relative, content in contents.items():
                prefix = f"skills/{packageName}/"
                if relative.startswith(prefix):
                    suffix = relative.removeprefix(prefix)
                    staged = stagedSkill.joinpath(*relativePath(suffix).parts)
                    installed = f"{skillRoot}/{packageName}/{suffix}"
                elif relative in ("install.py", "monitor.py"):
                    staged = stagedHelpers / relative
                    installed = f".community-feedback/bin/{relative}"
                else:
                    continue
                staged.parent.mkdir(parents=True, exist_ok=True)
                staged.write_bytes(content)
                staged.chmod(0o755 if staged.suffix == ".py" else 0o644)
                installedHashes[installed] = hashlib.sha256(content).hexdigest()
            stagedRecord = staging / "install.json"
            stagedRecord.write_text(json.dumps({"schemaVersion": 1, "name": packageName, "version": manifest["version"], "skillRoot": skillRoot, "files": installedHashes}, indent=2) + "\n", encoding="utf-8")
            destinations = [(stagedSkill, containedPath(project, f"{skillRoot}/{packageName}")), (stagedHelpers, containedPath(project, ".community-feedback/bin")), (stagedRecord, recordPath)]
            changes = []
            try:
                for index, (staged, target) in enumerate(destinations):
                    target.parent.mkdir(parents=True, exist_ok=True)
                    backup = staging / f"previous-{index}"
                    hadPrevious = target.exists()
                    if hadPrevious:
                        os.replace(target, backup)
                    changes.append((target, backup, hadPrevious))
                    os.replace(staged, target)
            except BaseException:
                for target, backup, hadPrevious in reversed(changes):
                    if target.is_dir():
                        shutil.rmtree(target)
                    elif target.exists():
                        target.unlink()
                    if hadPrevious:
                        os.replace(backup, target)
                raise
    return {"status": "installed", "version": manifest["version"], "skill": str(project / skillRoot / packageName), "monitor": str(project / ".community-feedback/bin/monitor.py"), "schedulerActivated": False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--project", type=pathlib.Path, required=True, help="Existing project directory; installation is project-local.")
    parser.add_argument("--harness", choices=tuple(skillRoots), required=True)
    parser.add_argument("--source", type=pathlib.Path, help="Local package directory containing manifest.json; omit to download from the fixed blog URL.")
    parser.add_argument("--update", action="store_true", help="Replace a previously installed, unmodified copy after verifying its hashes.")
    arguments = parser.parse_args()
    project = arguments.project.expanduser().resolve(strict=True)
    source = arguments.source.expanduser().resolve(strict=True) if arguments.source else None
    if not project.is_dir() or (source is not None and not source.is_dir()):
        raise ValueError("Project and source must be directories.")
    manifest, contents = readPackage(source)
    print(json.dumps(installPackage(project, arguments.harness, manifest, contents, arguments.update)))


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, urllib.error.URLError) as error:
        print(f"Installation failed: {error}", file=sys.stderr)
        sys.exit(1)
