"""Figure 1. The hypothesis loop, its scientific teams and campaign scale."""
import json

import numpy as np

from matplotlib.lines import Line2D
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from matplotlib.transforms import Affine2D
from geometry import draw_cell
from make_figures import rows
from plate import Plate, ROOT

p = Plate(192)
ink, muted, wire = '#192638', '#4f5c71', '#718096'
pink, indigo = '#c72c6a', '#5363a7'
band, rule, lavender = '#f5f6fa', '#d9dee9', '#e9ecf8'
white = '#ffffff'
mm = Affine2D().scale(1 / p.w, -1 / p.h).translate(0, 1) + p.f.transFigure
edges = {(r['from'], r['to']) for r in rows('methods/network_edges.csv')}
calls = {(r['caller'], r['callee']) for r in rows('data/agent_communication/delegation_edges.csv')}
work = rows('data/agent_communication/agent_workload.csv')
summary = json.loads((ROOT / 'methods/compute_summary.json').read_text())

def branch_roles(lead):
    roles = {lead}
    pending = [lead]
    while pending:
        parent = pending.pop()
        children = {target for caller, target in calls if caller == parent} - roles
        roles.update(children)
        pending.extend(children)
    return roles

design = {'geometry_generation', 'reaction_template_expert', 'hypothesis_generation_expert',
          'undermind_deep_research_expert'}
chemistry = branch_roles('computational_chemist')
modeling = {'quantum_physics'}
symbolic = {'sympy_expert'}
assert ('quantum_physics', 'sympy_expert') in calls
periodic = branch_roles('periodic_dft_expert')
groups = [design, chemistry, modeling, symbolic, periodic, {'molecular_discovery'}]
logged = {r['agent'] for r in work}
assert set.union(*groups) == logged and sum(map(len,groups)) == len(logged)
assert all(('molecular_discovery', agent) in calls for agent in design)
assert {('campaign_driver','molecular_discovery'),('molecular_discovery','campaign_ledger'),
        ('molecular_discovery','tool:judge_t1_loop'),('tool:judge_t1_loop','campaign_ledger'),
        ('molecular_discovery','tool:run_csp_funnel_workflow')} <= edges

# IDs retain the scientific grouping when the SVG opens in a drawing editor.
panel_a = 'a · Discovery network'
packing = 'b · Crystal structure prediction'
panel_c = 'c · Daily turns'
panel_d = 'd · Campaign resources'
layers = {}


def tag(artist, *path):
    key = f'part-{len(layers)}'
    artist.set_gid(key)
    layers[key] = path
    return artist


def label(path, x, y, s, size=7.2, color=ink, bold=False, align='left'):
    return tag(p.text(x, y, s, ha=align, fontsize=size, color=color,
                      weight='bold' if bold else 'normal', zorder=4), *path)


def box(path, x, y, w, h, fill, border, radius=1.7, level=1):
    patch = FancyBboxPatch((x, y), w, h, boxstyle=f'round,pad=0,rounding_size={radius}',
                           transform=mm, facecolor=fill, edgecolor=border,
                           linewidth=.7, zorder=level)
    p.f.add_artist(patch)
    tag(patch, *path)


def route(path, points, color=wire, start=False, end=True):
    xs, ys = zip(*points)
    line = Line2D(xs, ys, transform=mm, color=color, lw=.9,
                  solid_capstyle='butt', solid_joinstyle='round', zorder=2)
    p.f.add_artist(line)
    tag(line, *path)
    for enabled, tail, tip in [(start, points[1], points[0]), (end, points[-2], points[-1])]:
        if enabled:
            arrow = FancyArrowPatch(tail, tip, transform=mm, arrowstyle='-|>',
                                    shrinkA=0, shrinkB=0, mutation_scale=7.4,
                                    color=color, linewidth=.65, zorder=2)
            p.f.add_artist(arrow)
            tag(arrow, *path)


def control(x, width, title, note, fill, stroke, fg):
    path = (panel_a, 'Campaign control', title)
    box(path, x, 24, width, 15.5, fill, stroke, level=3)
    label(path, x+width/2, 29.4, title, 8.05, fg, True, 'center')
    label(path, x+width/2, 35, note, 6.95, fg, align='center')


def heading(panel, x, y, letter, title):
    path = (panel, 'Heading')
    label(path, x, y, letter, 11, bold=True)
    label(path, x+5.3, y, title, 9, bold=True)


heading(panel_a, 1, 3.7, 'a', 'A five-week search for longer spin lifetimes')
label((panel_a, 'Heading'), 179, 3.8, f'76 deployed agent nodes  ·  {len(logged)} logged roles',
      7.3, muted, align='right')
box((panel_a, 'Layer backgrounds'), 1, 9, 178, 35, band, rule, 2.4, 0)
box((panel_a, 'Layer backgrounds'), 1, 46.5, 178, 45, band, rule, 2.4, 0)
label((panel_a, 'Campaign control', 'Layer title'), 5, 14.3, 'Campaign control', 7.75, muted, True)
label((panel_a, 'Scientific teams', 'Layer title'), 5, 51.3, 'Scientific teams and tools', 7.75, muted, True)

control(5, 29, 'Job driver', 'Signals job completion', white, rule, ink)
control(43, 50, 'Discovery agent', 'Proposes the next test', pink, pink, white)
control(102, 36, 'Numerical validator', 'Recomputes spin lifetime', indigo, indigo, white)
control(146, 29, 'Campaign ledger', 'Stores signed verdicts', white, rule, ink)
control_links = (panel_a, 'Campaign control', 'Messages')
route(control_links, [(34,31.75),(43,31.75)])
route(control_links, [(93,31.75),(102,31.75)], indigo)
route(control_links, [(138,31.75),(146,31.75)], indigo)
for track, name in [
    ([(63,24),(63,13.8),(165,13.8),(165,24)], 'File forecast →'),
    ([(155,24),(155,20),(74,20),(74,24)], '← Read verdict'),
]:
    path = (*control_links, name)
    route(path, track, pink)
    height = track[1][1]
    box(path, 104, height-1.8, 22, 3.6, band, band, .2, 3)
    label(path, 115, height, name, 7.3, pink, align='center')

# Only Cuántico delegated the symbolic check; Teórica has no direct port on the bus.
teams = [
    (3, 24, 'Design support', 'Specialists', ('Hypotheses,', 'literature, synthesis')),
    (29, 23, 'Estructural', 'Multi-agent system', ('Builds molecular', 'structures')),
    (54, 22, 'Crystal packing', 'Workflow', ('Clari and UMA', 'screen packings')),
    (78, 20, 'Periodic DFT', 'Specialist', ('Crystal forces', 'and phonons')),
    (100, 29, 'Quntur', 'Multi-agent system', ('Runs ORCA to obtain', 'spin couplings')),
    (131, 21, 'Cuántico', 'Multi-agent system', ('Spin Hamiltonian', 'and rates')),
    (154, 23, 'Teórica', 'Multi-agent system', ('Checks equations', 'and physical limits')),
]
links = (panel_a, 'Scientific teams', 'Tasks and results')
ports = [x+w/2 for x,w,title,_,_ in teams if title != 'Teórica']
route(links, [(68,39.5),(68,55.5)], pink, start=True, end=False)
route(links, [(ports[0],55.5),(ports[-1],55.5)], end=False)
for port in ports:
    route(links, [(port,55.5),(port,60)])
for x,w,title,kind,description in teams:
    path = (panel_a, 'Scientific teams', title)
    is_system = kind == 'Multi-agent system'
    box(path, x, 60, w, 23.5, lavender if is_system else white, '#c9cfe6' if is_system else rule, level=3)
    label(path, x+1.2, 63.8, kind, 6.2, indigo if is_system else muted)
    label(path, x+1.2, 69.1, title, 7.5, bold=True)
    label(path, x+1.2, 75, description[0], 6.55)
    label(path, x+1.2, 79.2, description[1], 6.55)
derivations = (panel_a, 'Scientific teams', 'Symbolic derivations')
route(derivations, [(141.5,83.5),(141.5,88),(165.5,88),(165.5,83.5)], indigo)
# A small knockout keeps the label clear of the horizontal line.
box(derivations, 145.0, 86, 17.3, 4, band, band, .2, 3)
label(derivations, 153.5, 87.9, 'Derivations', 6.8, indigo, align='center')

for x, name, fill, border in [(24,'Discovery',pink,pink),(54,'Validation',indigo,indigo),
                              (86,'Multi-agent systems',lavender,'#b7bed9'),
                              (128,'Specialists and tools',white,'#a6afbf')]:
    path = (panel_a, 'Colour key', name)
    box(path, x, 94.6, 3.4, 2.7, fill, border, .55)
    label(path, x+5.4, 96, name, 7.15, muted)

# The three arrays depict the requested samples, not scores or different conformers.
heading(packing, 1, 104, 'b', 'How a salt design became a crystal model')
label((packing,'Heading'), 179,104,'6,798 trial packings across 22 counterions',
      7.4,muted,align='right')
box((packing,'Background'),1,109.5,178,32.4,band,rule,2.0,0)
clari=(packing,'CLARI-H · generate packings')
label(clari,5,114,'Clari generates packings',8.15,bold=True)
label(clari,5,119,'Typically 100 per cell size',7.35,muted)
for i,z in enumerate([1,2,4]):
    x=5.4+14*i
    key=(*clari,f'{z} formula units per cell')
    sample=tag(p.axes(x,122.4,8.5,8.5),*key)
    xx,yy=np.meshgrid(np.arange(10),np.arange(10))
    sample.scatter(xx,yy,s=1.7,marker='s',c=indigo,linewidths=0)
    sample.set(xlim=(-.6,9.6),ylim=(-.6,9.6),aspect='equal')
    sample.axis('off')
    label(key,x+4.25,133.8,f'{z}',7.2,align='center')
label(clari,5,138.3,'Formula units per cell',7.1,muted)
route((packing,'Selection'),[(47,126),(56,126)],indigo)
uma=(packing,'UMA · select packings')
label(uma,59,114,'UMA relaxes and ranks',8.15,bold=True)
label(uma,59,120,'300 K free-energy estimates',7.5,muted)
label(uma,59,128.3,'≤15 packings per salt',9.0,indigo,True)
route((packing,'Selection'),[(105,126),(114,126)],indigo)
dft=(packing,'Periodic DFT · refine structures')
label(dft,117,114,'DFT refines the shortlist',8.15,bold=True)
label(dft,117,127,'para-I cell',8.3,bold=True)
cell=tag(p.axes(138,116,38,23),*dft,'Predicted para-I crystal')
draw_cell(cell,'R5_pI',show_cations=True)

daily = rows('data/run_history_daily.csv')
turns = [int(r['orchestrator_turns']) for r in daily]
assert sum(turns) == summary['agent_turns'] and len(turns)==35
heading(panel_c, 1, 147, 'c', 'Daily discovery-agent turns')
ax = tag(p.axes(12.5,159.5,69,22), panel_c, 'Daily turns')
ax.bar(range(1,36), turns, color=pink, width=.77, lw=0, zorder=2)
ax.set(xlim=(.1,35.9), ylim=(0,26), yticks=[0,10,20], xticks=[1,7,14,21,28,35], xlabel='Campaign day')
ax.spines['left'].set_visible(False)
ax.tick_params(axis='y', length=0)
ax.set_axisbelow(True)
ax.grid(axis='y', color=rule, lw=.45)
heading(panel_d, 92, 147, 'd', 'Campaign resources')
metrics = [
    (format(summary['grand_total_cpu_core_h'],','),'CPU core-hours'),
    (f"{summary['grand_total_gpu_h']:.0f}",'GPU-hours'),
    (f"{summary['slurm_jobs_in_session']:,}",'scheduled jobs'),
    (f"{sum(float(r['output_tokens_M']) for r in work):.1f} million",'output tokens')]
for i,(value,unit) in enumerate(metrics):
    x,y=96+44*(i%2),159.5+17.4*(i//2)
    path=(panel_d,unit)
    label(path,x,y,value,14,bold=True)
    label(path,x,y+5.9,unit,7.6,muted)


p.save_layered_svg('01_agent_campaign', layers)
p.save('01_agent_campaign')
