#!/usr/bin/env python3
"""Read Jay Kang's local profile. Python 3.9+, standard library only."""
import argparse
import json
import sys
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--profile', type=Path, default=Path(__file__).with_name('profile.json'))
    parser.add_argument('--section', help='A top-level key such as projects, experience, or education')
    parser.add_argument('--list-sections', action='store_true')
    args = parser.parse_args()
    try:
        profile = json.loads(args.profile.read_text(encoding='utf-8'))
        if not isinstance(profile, dict):
            raise ValueError('The profile must contain a JSON object.')
        if args.list_sections:
            print('\n'.join(profile))
            return 0
        if args.section and args.section not in profile:
            raise ValueError('Unknown section. Available: ' + ', '.join(profile))
        print(json.dumps(profile[args.section] if args.section else profile, ensure_ascii=False, indent=2))
        return 0
    except (OSError, ValueError) as error:
        print('Could not read profile: ' + str(error), file=sys.stderr)
        return 1


if __name__ == '__main__':
    sys.exit(main())
