import falcon_kit.run_support
from falcon_kit import snakemake
from pypeflow.simple_pwatcher_bridge import (
    PypeProcWatcherWorkflow,
)
from .tasks import tasks_falcon_phase as tasks_falcon_phase
from . import io
import logging

LOG = logging.getLogger(__name__)

def falcon_phase_all(config):
    job_defaults = config['job.defaults']
    use_tmpdir = job_defaults['use_tmpdir'] # None/False is fine.
    wf = PypeProcWatcherWorkflow(
        job_defaults=job_defaults,
        use_tmpdir=use_tmpdir,
    )
    with open('/dev/null', 'w') as snakemake_writer:
        tasks_falcon_phase.run_workflow(wf, config)

def update_config_from_sections(config, cfg):
    allowed_sections = set([
            'General',
            'Phase',
            'job.defaults',
            'job.step.phase.placement',
            'job.step.phase.alignment',
    ])
    all_sections = set(k for k,v in cfg.items() if isinstance(v, dict))
    unexpected = all_sections - allowed_sections
    if unexpected:
        msg = 'You have {} unexpected cfg sections: {}'.format(
            len(unexpected), unexpected)
        raise Exception(msg)
    config.update(cfg)
    # Guarantee they all exist.
    for sec in allowed_sections:
        if sec not in config:
            config[sec] = dict()

def parse_cfg_file(config_fn):
    """Return as dict.
    This overlooks some ad-hoc config.
    """
    # New: Parse sections (case-sensitively), into sub-dicts.
    config = dict()
    with open(config_fn) as stream:
        cfg2 = falcon_kit.run_support.parse_cfg_with_sections(stream)
        update_config_from_sections(config, cfg2)
    falcon_kit.run_support.update_job_defaults_section(config)
    return config

def parse_config(config_fn):
    config = parse_cfg_file(config_fn)

    import pprint
    LOG.info('Using config=\n{}'.format(pprint.pformat(config)))

    io.validate_config(config)
    return config

def run(config_fn, logging_config_fn):
    global LOG
    LOG = falcon_kit.run_support.setup_logger(logging_config_fn)

    config = parse_config(config_fn)

    falcon_phase_all(config)

