"""
Script to generate markdown document from our config specification
"""
import toml
import os

script_path = os.path.dirname(os.path.realpath(__file__))
cfg_path = os.path.join(script_path,
        "..", "internal", "config_specification.toml"
)

with open(cfg_path, 'r') as fh:
    config = toml.loads(fh.read())

switches = config['switch']
params = config['param']

parsed = switches + params
parsed.sort(key=lambda x: x.get('name'))

print("# Configuration parameters")
print(f"<!-- This file is auto-generated by {__file__}, manual changes will be lost. -->")
print(f"<!-- AI AGENT: Do not update this file. -->")

print("""
You can specify options via command-line parameters, environment variables or using config files.

## Configuration files and environment variables

The config files must be in the Toml format. These config files are (from lowest priority to highest): `/etc/rostrum/config.toml`, `~/.rostrum/config.toml`, `./rostrum.toml`.

The options in highest-priority config files override options set in lowest-priority config files. Environment variables override options in config files and finally arguments override everythig else.

For each argument an environment variable of the same name with `ROSTRUM_` prefix, upper case letters and underscores instead of hypens exists (e.g. you can use `ROSTRUM_ELECTRUM_RPC_ADDR` instead of `--electrum-rpc-addr`). Similarly, for each argument an option in config file exists with underscores instead o hypens (e.g. `electrum_rpc_addr`). In addition, config files support `cookie` option to specify cookie - this is not available using command line or environment variables for security reasonns (other applications could read it otherwise).

Finally, you need to use a number in config file if you want to increase verbosity (e.g. `verbose = 3` is equivalent to `-vvv`) and `true` value in case of flags (e.g. `timestamp = true`)

""")

print("## Parameters ")
print("|Parameter name|Description|Default value|")
print("|--------------|-----------|-------------|")
for p in parsed:
    # Handle switches vs parameters differently
    if 'default' in p and p.get('default') == True:
        # Switch with default = true: use --no-X to disable
        param = f"`--no-{p.get('name')}`"
        param = param.replace('_', '-')
        abbr = p.get('abbr')
        if abbr is not None:
            param += f", `--{abbr}`"
    else:
        # Regular parameter or switch with default = false: use --X
        param = f"`--{p.get('name')}`"
        param = param.replace('_', '-')
        abbr = p.get('abbr')
        if abbr is not None:
            param += f", `--{abbr}`"

    print(f"|{param}|{p.get('doc')}|{p.get('default', '')}|")
