#!/usr/bin/env python3
"""Search names and document text in the same private index for Files and the menu."""
import argparse
import base64
import html.parser
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import time
import urllib.parse
import xml.etree.ElementTree as ET
import zipfile

MAX_FILE = 20 * 1024 * 1024
MAX_TEXT = 1024 * 1024
FOLDERS = ('Desktop', 'Documents', 'Downloads', 'Music', 'Pictures', 'Videos')


def path_key(path):
    """SQLite TEXT needs UTF-8; retain other Unix path bytes as BLOB keys."""
    text = str(path)
    try:
        text.encode('utf-8')
        return text
    except UnicodeEncodeError:
        return os.fsencode(text)


def rg_path(path):
    key = path_key(path)
    return {'bytes': base64.b64encode(key).decode('ascii')} if isinstance(key, bytes) else {'text': key}


def read_error(path, error, errors=None):
    # Files' native collector recognizes ripgrep's OS-error diagnostic and exit 2.
    message = f'rg: {path}: {error.strerror} (os error {error.errno})\n'
    sys.stderr.write(message)
    if errors is not None:
        errors.append(message)


def readable(path, errors=None):
    # Check actual access, including ACLs, before using previously cached text.
    try:
        with path.open('rb'):
            return True
    except OSError as error:
        read_error(path, error, errors)
        return False


class PageText(html.parser.HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.parts, self.skip = [], 0

    def handle_starttag(self, tag, attrs):
        if tag in ('script', 'style'):
            self.skip += 1
        if tag in ('p', 'div', 'br', 'li', 'h1', 'h2', 'tr'):
            self.parts.append('\n')

    def handle_endtag(self, tag):
        if tag in ('script', 'style') and self.skip:
            self.skip -= 1

    def handle_data(self, data):
        if not self.skip:
            self.parts.append(data)


def extract(path, errors=None):
    path = Path(path)
    try:
        if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_FILE:
            return ''
        suffix = path.suffix.lower()
        if suffix in ('.docx', '.odt', '.xlsx', '.pptx'):
            with zipfile.ZipFile(path) as archive:
                names = archive.namelist()
                if len(names) > 4000:
                    return ''
                wanted = [n for n in names if n in ('word/document.xml', 'content.xml', 'xl/sharedStrings.xml') or (n.startswith('ppt/slides/slide') and n.endswith('.xml'))]
                parts, total = [], 0
                for name in wanted:
                    size = archive.getinfo(name).file_size
                    total += size
                    if total > 4 * MAX_TEXT:
                        return ''
                    root = ET.fromstring(archive.read(name))
                    parts.extend(root.itertext())
                return ' '.join(parts)[:MAX_TEXT]
        if suffix == '.pdf':
            # Decode untrusted PDFs without network or access to the person's other files.
            args = ['bwrap', '--unshare-all', '--die-with-parent', '--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin', '--symlink', 'usr/lib', '/lib', '--ro-bind-try', '/lib64', '/lib64', '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--ro-bind', str(path.resolve()), '/input', 'prlimit', '--as=536870912', '--cpu=4', 'pdftotext', '-f', '1', '-l', '200', '/input', '-']
            with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as process:
                # Output is bounded independently of the input size.
                output = process.stdout.read(MAX_TEXT + 1)
                if len(output) > MAX_TEXT:
                    process.kill()
                    return ''
                try:
                    process.wait(timeout=6)
                except subprocess.TimeoutExpired:
                    process.kill()
                    return ''
                return output.decode('utf-8', 'replace') if process.returncode == 0 else ''
        # Like ripgrep, recognize ordinary text by its contents, including source,
        # configuration and extensionless files. Keep the same extraction bounds.
        with path.open('rb') as stream:
            data = stream.read(MAX_TEXT)
        if b'\0' in data:
            return ''
        text = data.decode('utf-8', 'replace')
        if suffix in ('.html', '.htm'):
            parser = PageText()
            parser.feed(text)
            return ''.join(parser.parts)
        return text
    except OSError as error:
        read_error(path, error, errors)
        return ''
    except (ValueError, ET.ParseError, zipfile.BadZipFile, subprocess.SubprocessError):
        return ''
    return ''


def recent_paths(home=None):
    home = Path(home or Path.home())
    path = Path(os.environ.get('XDG_DATA_HOME', home / '.local/share')) / 'recently-used.xbel'
    try:
        if path.stat().st_size > 8 * MAX_TEXT:
            return {}
        root = ET.parse(path).getroot()
        return {urllib.parse.unquote(urllib.parse.urlsplit(b.get('href', '')).path): b.get('visited', b.get('modified', '')) for b in root.findall('bookmark') if b.get('href', '').startswith('file:///')}
    except (OSError, ET.ParseError):
        return {}


def connect(cache=None):
    path = Path(cache or Path(os.environ.get('XDG_CACHE_HOME', Path.home() / '.cache')) / 'starchaser/files-index.sqlite')
    try:
        path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
        db = sqlite3.connect(path, timeout=2)
        path.chmod(0o600)
    except (OSError, sqlite3.Error):
        db = sqlite3.connect(':memory:')
    db.execute('CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, stamp TEXT, body TEXT)')
    # Re-extract unchanged text that older helpers omitted because of its suffix.
    if db.execute('PRAGMA user_version').fetchone()[0] != 1:
        db.execute('DELETE FROM files')
        db.execute('PRAGMA user_version=1')
        db.commit()
    return db


def files_under(roots, hidden=False, include_dirs=False, errors=None):
    for root in roots:
        root = Path(root)
        if not root.is_dir() or root.is_symlink():
            continue
        # Let ripgrep apply .gitignore, .ignore and global rules, including negations
        # and rules above the search root. NUL framing preserves every valid filename.
        argv = ['rg', '--no-config', '--files', '--null', '--no-require-git']
        if hidden:
            argv.append('--hidden')
        listed = subprocess.run([*argv, '--', '.'], cwd=root, capture_output=True)
        if listed.returncode == 2:
            # ripgrep still lists readable files when it skips an inaccessible path.
            # Preserve its diagnostics and partial status for Files' native collector.
            sys.stderr.write(os.fsdecode(listed.stderr))
            if errors is not None:
                errors.append(listed.stderr)
        elif listed.returncode not in (0, 1):
            raise subprocess.CalledProcessError(listed.returncode, argv, stderr=listed.stderr)
        allowed = {Path(os.fsdecode(name)) for name in listed.stdout.split(b'\0') if name}
        for folder, dirs, files in os.walk(root, followlinks=False):
            dirs[:] = [d for d in dirs if (hidden or not d.startswith('.')) and not (Path(folder) / d).is_symlink()]
            if include_dirs:
                # Folder names remain searchable even when the folder is empty.
                for name in dirs:
                    path = Path(folder) / name
                    yield path, 'directory'
            for name in files:
                path = Path(folder) / name
                if (not hidden and name.startswith('.')) or path.relative_to(root) not in allowed or path.is_symlink():
                    continue
                try:
                    meta = path.stat()
                    if path.is_file() and readable(path, errors):
                        yield path, f'{meta.st_mtime_ns}:{meta.st_size}:{meta.st_ino}'
                except OSError as error:
                    read_error(path, error, errors)


def update(db, roots, hidden=False):
    seen, changed = set(), 0
    for path, stamp in files_under(roots, hidden, include_dirs=True):
        key = path_key(path.absolute())
        old = db.execute('SELECT stamp FROM files WHERE path=?', (key,)).fetchone()
        if not old or old[0] != stamp:
            errors = []
            body = extract(path, errors)
            if errors:
                continue
            db.execute('INSERT OR REPLACE INTO files VALUES(?,?,?)', (key, stamp, body))
            changed += 1
            # A timed background pass keeps its progress, so large libraries finish over successive passes.
            if changed % 8 == 0:
                db.commit()
        seen.add(key)
    # Remove entries absent from this scan, including paths no longer accessible.
    # A later scan re-extracts them if access is restored.
    for (path,) in db.execute('SELECT path FROM files').fetchall():
        if any(Path(os.fsdecode(path)).is_relative_to(Path(r).absolute()) for r in roots) and path not in seen:
            db.execute('DELETE FROM files WHERE path=?', (path,))
    db.commit()


def search(db, query, roots, recent=None, limit=50, contents_only=False):
    needle, recent = query.casefold(), recent or {}
    found = []
    if not needle:
        return found
    for path, body in db.execute('SELECT path,body FROM files'):
        # The menu launches Unicode paths. Files' native search below can retain
        # arbitrary Unix bytes and mark names that cannot be operated on safely.
        if isinstance(path, bytes):
            continue
        p = Path(path)
        if not any(p.is_relative_to(Path(root).absolute()) for root in roots) or p.is_symlink() or not (p.is_file() or p.is_dir()):
            continue
        if contents_only and p.is_dir():
            continue
        if p.is_file() and not readable(p):
            continue
        name_match = needle in p.name.casefold()
        if not ((name_match and not contents_only) or needle in body.casefold()):
            continue
        line_no, line = next(((i, text.strip()) for i, text in enumerate(body.splitlines(), 1) if needle in text.casefold()), (1, p.name))
        found.append({'path': path, 'name': p.name, 'folder': str(p.parent.relative_to(Path.home())) if p.is_relative_to(Path.home()) else str(p.parent), 'line': line[:500], 'line_no': line_no, 'recent': path in recent, 'visited': recent.get(path, '')})
    found.sort(key=lambda r: (not r['recent'], ''.join(chr(0x10ffff - ord(c)) for c in r['visited']), r['name'].casefold(), r['path']))
    return found[:limit]


def rg_output(query, root='.', hidden=False, index=None):
    root = Path(root).absolute()
    cached = None
    if index:
        try:
            cached = sqlite3.connect(Path(index).as_uri() + '?mode=ro', uri=True, timeout=2)
        except (OSError, ValueError, sqlite3.Error):
            pass
    scanned, matches, needle = 0, 0, query.casefold()
    errors = []
    try:
        for path, stamp in files_under([root], hidden, errors=errors):
            scanned += 1
            row = None
            if cached:
                try:
                    row = cached.execute('SELECT stamp,body FROM files WHERE path=?', (path_key(path),)).fetchone()
                except sqlite3.Error:
                    pass
            body = row[1] if row and row[0] == stamp else extract(path, errors)
            if not needle or needle not in body.casefold():
                continue
            line_no, line = next(((i, text.strip()) for i, text in enumerate(body.splitlines(), 1) if needle in text.casefold()), (1, path.name))
            print(json.dumps({'type': 'match', 'data': {'path': rg_path(os.path.relpath(path, root)), 'lines': {'text': line[:500] + '\n'}, 'line_number': line_no, 'submatches': []}}), flush=True)
            matches += 1
    finally:
        if cached:
            cached.close()
    print(json.dumps({'type': 'summary', 'data': {'stats': {'searches': scanned}}}))
    return 2 if errors else (0 if matches else 1)


def main(argv):
    if '--rg' in argv:
        tail = argv[argv.index('--') + 1:]
        return rg_output(tail[0], tail[1] if len(tail) > 1 else '.', '--hidden' in argv, next((a.split('=', 1)[1] for a in argv if a.startswith('--index=')), None))
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('query', nargs='?', default='')
    parser.add_argument('--root', action='append')
    parser.add_argument('--update', action='store_true')
    args = parser.parse_args(argv)
    roots = args.root or [str(Path.home() / name) for name in FOLDERS]
    db = connect()
    if args.update or db.execute('SELECT count(*) FROM files').fetchone()[0] == 0:
        update(db, roots)
    if not args.update:
        print(json.dumps(search(db, args.query, roots, recent_paths(), 8)))
    return 0


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