#!/usr/bin/env python3
"""fpcalc-compatible fingerprint tool built on ffmpeg's chromaprint muxer.

AlmaLinux 9 ships libchromaprint but no fpcalc binary (the chromaprint-tools
package is not in base, EPEL or CRB). ffmpeg can emit the very same fingerprint
through its chromaprint muxer, so this shim gives every consumer of fpcalc
(beets chroma, pyacoustid, any script) a working implementation.

Supported arguments mirror the ones tools actually pass:
    fpcalc [-json] [-length SECONDS] FILE
"""
import json
import subprocess
import sys


def main(argv):
    path = None
    length = None
    as_json = False

    args = argv[1:]
    i = 0
    while i < len(args):
        a = args[i]
        if a in ("-json", "-json=1"):
            as_json = True
        elif a in ("-length", "-l"):
            i += 1
            length = args[i] if i < len(args) else None
        elif a in ("-raw", "-plain", "-text"):
            as_json = False
        elif a.startswith("-"):
            pass
        else:
            path = a
        i += 1

    if not path:
        sys.stderr.write("fpcalc: no input file\n")
        return 2

    # -vn: embedded cover art that this ffmpeg cannot decode must not decide
    # whether a track can be fingerprinted (it is audio we care about).
    cmd = ["ffmpeg", "-v", "quiet", "-nostdin", "-i", path]
    if length and length.isdigit() and int(length) > 0:
        cmd += ["-t", length]
    # Audio only: embedded cover art that this ffmpeg cannot decode must not
    # decide whether a track can be fingerprinted.
    cmd += ["-vn", "-map", "0:a", "-f", "chromaprint", "-fp_format", "base64", "-"]

    proc = subprocess.run(cmd, capture_output=True, text=True)
    fingerprint = proc.stdout.strip()

    dur = subprocess.run(
        ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
         "-of", "default=nw=1:nk=1", path],
        capture_output=True, text=True).stdout.strip()
    try:
        duration = int(float(dur))
    except (TypeError, ValueError):
        duration = 0

    if fingerprint:
        if as_json:
            print(json.dumps({"duration": duration, "fingerprint": fingerprint}))
        else:
            print("DURATION=%d" % duration)
            print("FINGERPRINT=%s" % fingerprint)
        return 0

    sys.stderr.write("fpcalc: could not fingerprint %s: %s\n" % (path, proc.stderr.strip()[:200]))
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
