import argparse
import json

from app.services.media import MediaService
from app.services.repository import get_repository
from app.services.store import JsonStore


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('recording_id')
    parser.add_argument('--convert-only', action='store_true')
    args = parser.parse_args()

    repo = get_repository()
    store = JsonStore()
    media = MediaService()

    recordings = repo.list_recordings()
    current = next((item for item in recordings if str(item.get('id')) == str(args.recording_id)), None)
    if not current:
        raise SystemExit(f'recording not found: {args.recording_id}')

    wav_path = current.get('stored_path')
    mp3_path = current.get('mp3_path') or media.planned_mp3_path(wav_path)
    result = media.convert_wav_to_mp3(wav_path, mp3_path)

    updates = {
        'conversion_status': result['status'],
        'conversion_result': result,
        'updated_at': store.now(),
    }
    if result['status'] == 'ok':
        updates['mp3_path'] = mp3_path
        delete_result = media.delete_source_if_requested(wav_path, bool(current.get('delete_wav_after_success')))
        updates['delete_source_result'] = delete_result
        if not args.convert_only:
            updates['status'] = 'converted'
    repo.update_recording(str(current.get('id')), updates)
    print(json.dumps({'recording_id': current.get('id'), 'result': result, 'updates': updates}, indent=2))


if __name__ == '__main__':
    main()
