from pathlib import Path
from fnmatch import fnmatchcase


def build_catalog(source, destination, exclude=()):
    root=Path(source)
    paths=[path for path in root.rglob('*') if path.is_file() and path.suffix=='.txt'
           and not any(fnmatchcase(path.relative_to(root).as_posix(),pattern) for pattern in exclude)]
    chosen=sorted((path.relative_to(root).as_posix(),path) for path in paths)
    output=Path(destination)
    output.mkdir()
    for name,path in chosen:
        target=output/'files'/name
        target.parent.mkdir(parents=True,exist_ok=True)
        target.write_bytes(path.read_bytes())
    payload=''.join(name+'\n' for name,_ in chosen)
    (output/'index.txt').write_text(payload,encoding='utf-8',newline='\n')
    return 1
