#!/usr/bin/env python3

"""Reads an iXBRL file on input, and outputs a JSON representation.
Two representations are supported: flat: outputs a list of contexts and
values; hierarchy: embeds contexts in related context which introduces a
natural grouping structure to related contexts.
"""

import datetime
from lxml import etree as ET
import sys
import argparse
import json

from ixbrl_parse.ixbrl import parse

maxwidth=40

parser = argparse.ArgumentParser(
    description=__doc__
)
parser.add_argument('input', metavar='input', nargs=1,
                    help='Input iXBRL file')
parser.add_argument('--format', '-f',
                    default="hierarchy",
                    help="Output format, one of: flat, hierarchy, labels (default: hierarchy)")
parser.add_argument('--base-url', '-base', '-u',
                    help='Base URL for further schema fetches')

# Parse arguments
args = parser.parse_args(sys.argv[1:])

tree = ET.parse(args.input[0])

i = parse(tree)

if args.format == "flat":
    rels = i.flatten()
elif args.format == "hierarchy":
    rels = i.to_dict()
elif args.format == "labeled":
    rels = i.to_dict(i.load_schema(args.base_url))
else:
    raise RuntimeError("Format %s not known" % args.format)

print(json.dumps(rels, indent=4))

