"""Feasibility probe on the existing four-vCPU host: full network construction plus a short
spontaneous segment, with timing and memory recorded.

The model, parameters, seeds and 16 virtual processes are those of the declared run; the split
into MPI ranks and threads is given on the command line (16x1 as declared, or e.g. 4x4). The only change is
the duration of the single NoStimulation segment, read from FELISYN_PROBE_MS instead of 40,320 ms.
The workflow's 150 ms initial, reset and end blanks are unchanged. This measures whether a full
run on this host is practical; it is not the full-model experiment.

  FELISYN_MODEL=/opt/felisyn/protocol-006/model FELISYN_OUT=/path/probe.json FELISYN_PROBE_MS=140 \
  mpirun --oversubscribe -np 16 python probe_feasibility.py nest 1 param_spont/defaults \
      results_dir "'/path/results/'" trial 0 felisyn_feasibility_probe
"""
import json, os, resource, sys, time
from pathlib import Path

MODEL = Path(os.environ['FELISYN_MODEL']).resolve()
OUT = Path(os.environ['FELISYN_OUT']).resolve()
PROBE_MS = int(os.environ['FELISYN_PROBE_MS'])
assert PROBE_MS % 7 == 0, 'Keep the duration a multiple of the 7 ms frame used by the released protocols'
sys.path.insert(0, str(MODEL))
os.chdir(MODEL)

from mpi4py import MPI
comm = MPI.COMM_WORLD
import nest
nest.Install('stepcurrentmodule')
from parameters import ParameterSet
from model import SelfSustainedPushPull
from mozaik.experiments import NoStimulation
from mozaik.controller import prepare_workflow, run_experiments

marks = {}


def mark(name):
    comm.Barrier()
    marks[name] = time.time()
    if comm.rank == 0:
        print(f'FELISYN-MARK {name} {time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(marks[name]))}', flush=True)


def kernel(keys):
    status = nest.GetKernelStatus()
    return {k: status[k] for k in keys if k in status} | {k: status[k] for k in status if str(k).startswith('time_')}


mark('start')
sim, num_threads, parameters = prepare_workflow('SelfSustainedPushPull', SelfSustainedPushPull)
assert comm.Get_size() * int(num_threads) == 16, 'Keep the 16 virtual processes of the declared run'
mark('prepared')
model = SelfSustainedPushPull(sim, num_threads, parameters)
mark('constructed')
after_build = {'maxrss_kib': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
               'kernel': kernel(['num_connections', 'network_size', 'local_num_threads', 'total_num_virtual_procs'])}
experiments = [NoStimulation(model, ParameterSet({'duration': PROBE_MS}))]
data_store = run_experiments(model, experiments, parameters)
mark('simulated')
after_sim = {'maxrss_kib': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, 'kernel': kernel(['biological_time'])}
if comm.rank == 0:
    data_store.save()
mark('saved')
per_rank = comm.gather({'rank': comm.rank, 'after_build': after_build, 'after_simulation': after_sim,
                        'final_maxrss_kib': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss}, root=0)
if comm.rank == 0:
    log = data_store.block.annotations['simulation_log']
    simulated_ms = PROBE_MS + 3 * float(parameters.null_stimulus_period)
    phases = {'prepare_s': marks['prepared'] - marks['start'], 'construct_s': marks['constructed'] - marks['prepared'],
              'simulate_s': marks['simulated'] - marks['constructed'], 'save_s': marks['saved'] - marks['simulated']}
    result = {
        'scope': 'Feasibility probe: unchanged model, parameters and seeds, 16 virtual processes; NoStimulation shortened. Not the full-model experiment.',
        'mpi_ranks': comm.Get_size(), 'threads_per_rank': int(num_threads),
        'probe_ms': PROBE_MS,
        'simulated_ms_including_blanks': simulated_ms,
        'phases_wall_seconds': phases,
        'wall_seconds_per_simulated_second': phases['simulate_s'] / (simulated_ms / 1000.0),
        'explosion_detected': bool(log['explosion_detected']),
        'marks_utc_epoch': marks,
        'per_rank': per_rank,
        'sum_final_maxrss_gib': sum(r['final_maxrss_kib'] for r in per_rank) / 2 ** 20,
        'max_rank_final_maxrss_gib': max(r['final_maxrss_kib'] for r in per_rank) / 2 ** 20,
        'note': 'ru_maxrss is per-process peak resident memory; the sum over ranks overstates simultaneous use and excludes swapped pages. Host-level samples are in resources.csv.',
    }
    OUT.write_text(json.dumps(result, indent=2, default=str) + '\n')
    print(json.dumps({k: result[k] for k in ['phases_wall_seconds', 'wall_seconds_per_simulated_second', 'explosion_detected', 'sum_final_maxrss_gib']}, default=str), flush=True)
comm.Barrier()
