#!/usr/bin/env python3
"""Copy a selected local image into the user's portable shell configuration."""
import hashlib
import os
from pathlib import Path
import sys
import tempfile
from urllib.parse import unquote, urlsplit
import xml.etree.ElementTree as ET


def import_image(value):
    url = urlsplit(value)
    if url.scheme != 'file' or url.netloc not in ('', 'localhost'):
        raise ValueError('Select a local image')
    source = Path(unquote(url.path)).resolve(strict=True)
    if not source.is_file() or source.stat().st_size > 32 * 1024 * 1024:
        raise ValueError('Image is missing or too large')
    data = source.read_bytes()
    if data.startswith(b'\x89PNG\r\n\x1a\n') and len(data) > 32:
        extension = '.png'
    elif data.startswith(b'\xff\xd8\xff'):
        extension = '.jpg'
    elif data.startswith(b'RIFF') and data[8:12] == b'WEBP':
        extension = '.webp'
    elif source.suffix.lower() == '.svg':
        tree = ET.fromstring(data)
        if tree.tag != '{http://www.w3.org/2000/svg}svg':
            raise ValueError('Not an SVG image')
        extension = '.svg'
    else:
        raise ValueError('Unsupported image')
    config = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config'))
    directory = config / 'quickshell/default/img/custom'
    directory.mkdir(parents=True, exist_ok=True)
    destination = directory / ('start-orb-' + hashlib.sha256(data).hexdigest()[:20] + extension)
    fd, temporary = tempfile.mkstemp(prefix='.orb-', dir=directory)
    try:
        with os.fdopen(fd, 'wb') as stream:
            stream.write(data)
        os.replace(temporary, destination)
    finally:
        Path(temporary).unlink(missing_ok=True)
    return destination.as_uri()


if __name__ == '__main__':
    try:
        if len(sys.argv) != 2:
            raise ValueError('Select one image')
        print(import_image(sys.argv[1]))
    except (OSError, ValueError, ET.ParseError) as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
