"""Inbox.Cheap skill installer. Python 3.10+, standard library only."""
import argparse
import hashlib
import io
from pathlib import Path
import shutil
import sys
import tempfile
import urllib.request
import zipfile

VERSION = '1.2.0'
URL = 'https://inboxcheap.com/downloads/inboxcheap-skill-1.2.0.zip'
SHA256 = '89e58388d676bc476af3a95e8ee761bd0272d0ae217e2e64806db52e3159509e'
FILES = ('SKILL.md', 'scripts/inbox.py')

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

def read_package(data):
    if hashlib.sha256(data).hexdigest() != SHA256:
        raise ValueError('Package checksum mismatch; installation stopped.')
    output = {}
    with zipfile.ZipFile(io.BytesIO(data)) as package:
        for info in package.infolist():
            name = info.filename.replace('\\', '/')
            if info.is_dir():
                continue
            if name not in {'inboxcheap/' + path for path in FILES} or info.file_size > 1000000:
                raise ValueError('Unexpected package file; installation stopped.')
            path = name[len('inboxcheap/'):]
            if path in output or ((info.external_attr >> 16) & 0o170000) == 0o120000:
                raise ValueError('Duplicate file or symlink in package.')
            output[path] = package.read(info)
    if set(output) != set(FILES):
        raise ValueError('Package is incomplete.')
    return output

def install(files, base):
    base = base.expanduser().absolute()
    if any(p.is_symlink() for p in [base, *base.parents]):
        raise ValueError('Choose a skills directory without symlinks.')
    base.mkdir(parents=True, exist_ok=True)
    target = base / 'inboxcheap'
    if target.is_symlink():
        raise ValueError('Existing skill is a symlink; installation stopped.')
    if target.exists():
        existing = {str(p.relative_to(target)).replace('\\', '/') for p in target.rglob('*') if p.is_file()}
        if any(p.is_symlink() for p in target.rglob('*')):
            raise ValueError('Existing skill contains a symlink.')
        if existing == set(FILES) and all((target / path).read_bytes() == data for path, data in files.items()):
            return target, 'Already installed'
        raise ValueError('A different inboxcheap skill already exists. Move it aside before installing; no files were overwritten.')
    stage = Path(tempfile.mkdtemp(prefix='.inboxcheap-install-', dir=base))
    try:
        for path, data in files.items():
            dest = stage / path
            dest.parent.mkdir(parents=True, exist_ok=True)
            dest.write_bytes(data)
        # Refuse to replace a directory created concurrently.
        if target.exists():
            raise ValueError('Destination appeared during installation; try again.')
        stage.rename(target)
        return target, 'Installed'
    finally:
        if stage.exists():
            shutil.rmtree(stage)

def main():
    if sys.version_info < (3, 10):
        raise ValueError('Python 3.10 or newer is required.')
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--dir', type=Path, required=True, help='Explicit absolute skills directory for your current agent')
    args = parser.parse_args()
    if not args.dir.is_absolute():
        parser.error('--dir must be an absolute directory for your current agent.')
    request = urllib.request.Request(URL, headers={'User-Agent': 'Mozilla/5.0 (compatible; InboxCheapInstaller/1.0)'})
    with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
        data = response.read(2000001)
    if len(data) > 2000000:
        raise ValueError('Package exceeds download limit.')
    files = read_package(data)
    target, status = install(files, args.dir)
    print(f'{status}: Inbox.Cheap skill {VERSION}\nLocation: {target}')
    print('Next: configure INBOXCHEAP_API_KEY privately in the environment of your agent, then start a new agent session.')
    print('New inbox workflows: mailboxes:read, mailboxes:write, messages:read, codes:read.')
    print('Connected personal inbox: use its dedicated read-only key; mailbox creation permission is not needed.')
    print('No API keys were requested, stored, or transmitted by this installer.')

if __name__ == '__main__':
    try:
        main()
    except Exception as error:
        print(f'Installation failed: {error}', file=sys.stderr)
        sys.exit(1)
