#!/usr/bin/env python3 """ Fix JRiver date imported fields to use the earliest date for each album. """ import sys from pathlib import Path, PureWindowsPath def get_album_path(line: str) -> str: """Extract and return the album directory path from a filename field.""" filename = line.lstrip('').rstrip('\n') path = PureWindowsPath(filename) return str(path.parent) def get_date(line: str) -> int: """Extract and return the date imported value from a date field.""" date = line.lstrip('').rstrip('\n') return int(date) def main() -> None: """Main function to process JRiver library file.""" if len(sys.argv) != 3: print("Usage: jriver-fix-date-imported ", file=sys.stderr) sys.exit(1) in_file = Path(sys.argv[1]) out_file = Path(sys.argv[2]) if not in_file.exists(): print(f"[ERROR] Input file '{in_file}' does not exist.", file=sys.stderr) sys.exit(1) # Read input file with open(in_file, "r", encoding="utf-8") as f: lines = f.readlines() # Build album to tracks mapping albums: dict[str, list[tuple[int, int]]] = {} current_album: str | None = None for lnum, line in enumerate(lines): if '' in line: current_album = get_album_path(line) elif '' in line: date = get_date(line) if current_album: albums.setdefault(current_album, []).append((lnum, date)) # Update lines with earliest date for each album for _, tracks in albums.items(): earliest_date: int = min(tracks, key=lambda t: t[1])[1] for lnum, _ in tracks: lines[lnum] = f'{earliest_date}\n' # Write output file with open(out_file, 'w', encoding="utf-8") as f: f.writelines(lines) print(f"[SUCCESS] Processed {len(albums)} albums. Output written to '{out_file}'.") if __name__ == "__main__": main()