"""Inspect/import one PCM WAV, then append its exact MediaPool ID in a separate run."""
import argparse
from resolve_api_connection import connect
from resolve_api_delivery import (cli_write, inspect_wav, current, folder_state,
                                  audio_action, print_result)


def main():
    p = argparse.ArgumentParser(description=__doc__)
    cli_write(p)
    p.add_argument('--step', choices=['inspect','import','append'], default='inspect')
    p.add_argument('--file', required=True, help='Absolute trusted local PCM WAV; at most 512 MiB')
    p.add_argument('--folder-id'); p.add_argument('--media-id')
    p.add_argument('--track-index',type=int,default=1)
    p.add_argument('--record-frame',type=int,help='Absolute timeline record frame, not an audio sample index')
    a = p.parse_args()
    if a.step == 'inspect' and a.apply: p.error('inspect never applies a change')
    if a.step == 'append' and (not a.media_id or a.record_frame is None):
        p.error('append requires --media-id and --record-frame')

    def work():
        wav = inspect_wav(a.file)  # No connection until bounded PCM read succeeds.
        resolve = connect()
        if a.step == 'inspect':
            project, timeline, pid, tid = current(resolve,a.project_id,a.timeline_id)
            _, _, folder, _ = folder_state(project)
            return {'status':'observed','project_id':pid,'timeline_id':tid,
                    'origin':timeline.GetStartFrame(),'source':wav,'folder':folder,'mutations_sent':0}
        return audio_action(resolve, wav, project_id=a.project_id, timeline_id=a.timeline_id,
                            step=a.step, apply=a.apply, test_copy=a.test_copy,
                            expect_plan=a.expect_plan, audio_reviewed=a.audio_reviewed,
                            folder_id=a.folder_id, media_id=a.media_id,
                            track_index=a.track_index, record_frame=a.record_frame)
    return print_result(work)


if __name__ == "__main__":
    raise SystemExit(main())
