#!/usr/bin/env python3
# summary: Preview a capture, edit it, copy text, or make a smaller recording.
"""Screenshot and recording results: preview, open, edit, copy text and make smaller to share."""
import ctypes
import errno
import math
import os
import subprocess
import struct
import sys
import tempfile
import time
from pathlib import Path


def notify(title, body, *args):
    token = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / 'starchaser-notifications' / 'token'
    cmd = ['starchaser', 'notify', '-a', 'Starchaser', *args, title, body]
    if token.is_file():
        with token.open('rb') as proof:
            return subprocess.run([*cmd[:2], f'--credential-fd={proof.fileno()}', *cmd[2:]], pass_fds=(proof.fileno(),), capture_output=True, text=True).stdout.strip()
    return subprocess.run(cmd, capture_output=True, text=True).stdout.strip()


def cache():
    folder = Path(os.environ.get('XDG_CACHE_HOME', Path.home() / '.cache')) / 'starchaser/captures'
    folder.mkdir(parents=True, exist_ok=True, mode=0o700)
    # The notification history keeps a week. Prune only our generated cache pictures after that.
    for picture in folder.glob('*.png'):
        try:
            if picture.is_file() and picture.stat().st_mtime < time.time() - 7 * 86400:
                picture.unlink()
        except OSError:
            pass  # Cleanup must not prevent a new capture result.
    return folder


def capture_hints(path, kind):
    hints = ['-h', 'string:x-starchaser-capture:' + kind, '-h', 'string:image-path:' + str(path)]
    try:
        with Path(path).open('rb') as picture:
            header = picture.read(24)
        if len(header) == 24 and header[:16] == b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR':
            width, height = struct.unpack('>II', header[16:24])
            if 0 < width <= 0x7fffffff and 0 < height <= 0x7fffffff:
                hints += ['-h', f'int:x-starchaser-capture-width:{width}', '-h', f'int:x-starchaser-capture-height:{height}']
    except OSError:
        pass  # A missing preview must not hide the saved capture or its actions.
    return hints


def edit(path):
    fd, name = tempfile.mkstemp(prefix=path.stem + '-edited-', suffix='.png', dir=path.parent)
    os.close(fd)
    target = Path(name)
    target.unlink()  # Cancel must not copy an empty file or an edit from an earlier session.
    result = subprocess.run(['satty', '--filename', str(path), '--output-filename', str(target)])
    if result.returncode:
        raise OSError("The picture editor couldn't open.")
    if target.is_file() and target.stat().st_size:
        with target.open('rb') as picture:
            subprocess.run(['wl-copy', '--type', 'image/png'], stdin=picture, check=True)
        notify('Edited screenshot copied', 'Your edited picture is ready to paste.', '-i', str(target), *capture_hints(target, 'picture'))


def copy_text(path):
    result = subprocess.run(['tesseract', str(path), 'stdout', '-l', 'eng'], capture_output=True, text=True, check=True)
    text = result.stdout.strip()
    if not text:
        notify('No text found', 'Try a larger area around the words.')
        return
    subprocess.run(['wl-copy', '--type', 'text/plain'], input=text, text=True, check=True)
    notify('Text copied', 'Paste it where you want it.')


def share_update(notice, progress, message):
    args = ['-p', '-t', '0']
    if notice:
        args += ['-r', notice]
    if progress >= 0:
        args += ['-h', f'int:value:{round(progress * 100)}']
    title = 'Making a smaller recording' if 0 <= progress < 1 else 'Smaller recording ready' if progress == 1 else 'Recording could not be made smaller'
    return notify(title, message, *args)


def encode_share(path, target, progress):
    duration = float(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                                    '-of', 'default=noprint_wrappers=1:nokey=1', str(path)],
                                   capture_output=True, text=True, check=True).stdout.strip())
    if not math.isfinite(duration) or duration <= 0:
        raise OSError("The recording length couldn't be read.")
    with tempfile.TemporaryFile() as errors:
        with subprocess.Popen(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(path),
                               '-vf', "scale=w='min(1280,iw)':h='min(720,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2",
                               '-c:v', 'libx264', '-preset', 'fast', '-crf', '28', '-pix_fmt', 'yuv420p', '-fpsmax', '30',
                               '-c:a', 'aac', '-b:a', '128k', '-ac', '2', '-movflags', '+faststart',
                               '-progress', 'pipe:1', '-nostats', str(target)], stdout=subprocess.PIPE, stderr=errors, text=True) as process:
            last = -1
            for line in process.stdout:
                if line.startswith('out_time_us='):
                    try:
                        percent = min(99, max(0, int(float(line.split('=', 1)[1]) / 1e6 / duration * 100)))
                    except ValueError:
                        continue  # ffmpeg emits N/A before the first encoded frame.
                    if percent != last:
                        progress(percent / 100)
                        last = percent
            if process.wait():
                raise OSError("The video couldn't be converted. The original recording is kept.")


def format_size(size):
    for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
        if size < 1000 or unit == 'TB':
            return f'{size:.0f} {unit}' if size >= 10 or unit == 'B' else f'{size:.1f} {unit}'
        size /= 1000


def saved_folder(path):
    try:
        folder = path.parent.relative_to(Path.home())
        return str(folder) if folder.parts else 'Home folder'
    except ValueError:
        return str(path.parent)


def rename_exclusive(source, target):
    # Linux's no-replace rename also works on FAT/exFAT, which cannot make hard links.
    rename = ctypes.CDLL(None, use_errno=True).renameat2
    rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
    rename.restype = ctypes.c_int
    if rename(-100, os.fsencode(source), -100, os.fsencode(target), 1) != 0:  # AT_FDCWD, RENAME_NOREPLACE
        code = ctypes.get_errno()
        raise OSError(code, os.strerror(code), str(target))


def publish_smaller(temporary, original):
    # Both operations publish the complete file atomically without replacing files or symlinks.
    number = 1
    while True:
        suffix = '' if number == 1 else f' {number}'
        target = original.with_name(f'{original.stem} (smaller){suffix}.mp4')
        try:
            try:
                os.link(temporary, target)
            except OSError as error:
                if error.errno not in (errno.EOPNOTSUPP, errno.EPERM, errno.ENOSYS):
                    raise
                rename_exclusive(temporary, target)
            return target
        except FileExistsError:
            number += 1


def share(path):
    # A distinct destination and a temporary MP4 keep the original intact, including after an interrupted encode.
    fd, temporary = tempfile.mkstemp(prefix='.' + path.stem + '-share-', suffix='.mp4', dir=path.parent)
    os.close(fd)
    temporary = Path(temporary)
    notice = ''
    try:
        notice = share_update('', 0, 'Starting… Your original recording is kept.') or ''

        def progress(fraction):
            nonlocal notice
            notice = share_update(notice, fraction, f'{round(fraction * 100)}% · Your original recording is kept.') or notice

        encode_share(path, temporary, progress)
        if not temporary.stat().st_size:
            raise OSError('The smaller recording is empty.')
        if temporary.stat().st_size >= path.stat().st_size:
            args = ['-r', notice] if notice else []
            notify('The recording is already small', 'A smaller copy would not save space. Share the original.', *args)
            return
        temporary.chmod(path.stat().st_mode & 0o777)
        target = publish_smaller(temporary, path)
        temporary.unlink(missing_ok=True)
        sizes = f'{format_size(target.stat().st_size)} instead of {format_size(path.stat().st_size)} · {target.name} in {saved_folder(target)}'
        share_update(notice, 1, sizes)
        args = ['-r', notice] if notice else []
        action = notify('Smaller recording ready', sizes, *args, '-i', 'video-x-generic', '-A', 'open=Play', '-A', 'folder=Show in folder')
        if action == 'open':
            subprocess.Popen(['xdg-open', str(target)], start_new_session=True)
        elif action == 'folder':
            subprocess.Popen(['starchaser', 'files', str(target.parent)], start_new_session=True)
    except (OSError, ValueError, subprocess.SubprocessError):
        share_update(notice, -1, 'The conversion could not finish. Your original recording is kept. Try again.')
        return
    finally:
        temporary.unlink(missing_ok=True)


def recording(path):
    fd, thumbnail = tempfile.mkstemp(prefix='recording-', suffix='.png', dir=cache())
    os.close(fd)
    result = subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(path), '-frames:v', '1', '-vf', 'scale=360:-1', thumbnail], capture_output=True)
    icon = thumbnail if result.returncode == 0 and Path(thumbnail).stat().st_size else 'video-x-generic'
    preview = capture_hints(thumbnail, 'recording') if icon == thumbnail else []
    action = notify('Recording saved', path.name + f' · {format_size(path.stat().st_size)}\n{saved_folder(path)}', '-i', icon, *preview, '-A', 'open=Play',
                    '-A', 'share=Make it smaller to share', '-A', 'folder=Show in folder')
    if action == 'open':
        subprocess.Popen(['xdg-open', str(path)], start_new_session=True)
    elif action == 'share':
        share(path)
    elif action == 'folder':
        subprocess.Popen(['starchaser', 'files', str(path.parent)], start_new_session=True)


def main(args):
    if args in (['--help'], ['-h']):
        print('Usage: starchaser capture result screenshot|recording|edit|text|share FILE [MESSAGE [TITLE]]\nOpen, edit or share a finished capture. The original is kept.')
        return 0
    if len(args) not in (2, 3, 4) or args[0] not in ('screenshot', 'recording', 'edit', 'text', 'share'):
        print('Usage: starchaser capture result screenshot|recording|edit|text|share FILE [MESSAGE [TITLE]]', file=sys.stderr)
        return 2
    path = Path(args[1]).resolve()
    if not path.is_file():
        print('That capture is no longer available.', file=sys.stderr)
        return 1
    try:
        if args[0] == 'screenshot':
            cache()
            # The capture says where the picture went (saved and copied, or copied only); TITLE carries that.
            action = notify(args[3] if len(args) == 4 else 'Screenshot copied', args[2] if len(args) >= 3 else 'Paste it where you want it.', '-i', str(path), *capture_hints(path, 'picture'),
                            '-A', 'open=Open', '-A', 'edit=Edit', '-A', 'text=Copy text')
            if action == 'open':
                subprocess.Popen(['xdg-open', str(path)], start_new_session=True)
            elif action == 'edit':
                edit(path)
            elif action == 'text':
                copy_text(path)
        elif args[0] == 'recording':
            recording(path)
        elif args[0] == 'edit':
            edit(path)
        elif args[0] == 'text':
            copy_text(path)
        else:
            share(path)
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        message = 'The tool could not complete this action.' if isinstance(error, subprocess.SubprocessError) else str(error)
        notify('Capture action could not finish', 'Try again. ' + message)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
