"""Generate the reviewed map, exact entity documentation and stage inventory."""
from pathlib import Path
import json,re
from case_ui_model import MANIFESTS,LABELS
from build_operations_examples import LINKS
from agent_catalog import CATALOG,ENTITIES,PROFILE_IDS,entity_md,entity_url,build_catalog_docs,refresh_module_agent_tables,runs_code
from agent_map_svg import build_svg,ORDER,GATES,stage_title
from _paths import ARCH,SITE,DOCS_DIRNAME
HERE=Path(__file__).resolve().parent

def inventory():
    out=['# Stage Agents and Tools','',
    '**[P]** Each stage selects the methods and agent roles needed for its actual case. Definitions live on the module subpages linked below. The [Common catalogue](Common%20Capabilities.md) contains shared definitions only; the [module index](Agent%20Catalogue.md) contains references, not a second set of descriptions.','',
    '**[P]** A skill is an LLM-guided domain procedure. Its optional executable helpers are runnable source/binaries. Runtime/connector access and parent/agent-call protocols are not additional learned skills or fictional tools.','',
    '**[P]** [Intake](../Intake.md) is polling/push and durable event handling; Support root then classifies and routes. [Assessment & Offers](../45%20Commercial/Assessment%20and%20Offers.md) clarifies, assesses effort, prepares an offer, obtains the customer decision and communicates it. Core Development is an offer type and has no code pipeline.','',
    '**[P]** Agents consult one another in either direction through the [runtime communication protocol](Agents.md). A reply is evidence, not scope or authority. [Experience strategies](Experience%20Strategies.md) define case/domain retrieval and canonical memory indexing.','',
    '**[P]** What the v1 memory could still become — every candidate tool, skill and article with its seeds, owner and evidence — is inventoried on [Memory-derived capabilities](Memory%20Derived%20Capabilities.md); the board of the detailed view lists a profile\'s candidates beside its published methods.','']
    for module in ('support','data','configuration','source','commercial'):
        out += ['## '+MANIFESTS[module]['name'],'','| Stage | Selected agent choices | Completion / checkpoint |','|---|---|---|']
        for d in MANIFESTS[module]['stages']:
            sid=d['id']
            agents=[]
            for key in CATALOG['stages'][module+'/'+sid]['agents']:
                agents.append(entity_md(key))
            out.append('| '+stage_title(module,sid)+' ('+sid+') | '+', '.join(agents)+' | '+d['done'].replace('|','&#124;')+' |')
        out+=['']
    out+=['## Composition and implementation checks','']
    for finding in CATALOG['review_findings']:out+=['**[P]** '+finding,'']
    out+=['## Authoring sources','',
    '[Map renderer](../ui/agent_map_svg.py) · [Build entry](../ui/build_agent_map.py) · [Catalogue renderer](../ui/agent_catalog.py) · [Source validator](../ui/validate_agent_map.py).','']
    (ARCH/'50 Agents/Stage Agents and Tools.md').write_text('\n'.join(out),encoding='utf-8')

def build():
    drawing=build_svg()
    (SITE/'assets/agent-map.svg').write_text(drawing,encoding='utf-8')
    p=SITE/'index.html';page=p.read_text(encoding='utf-8')
    block='<!-- BEGIN DETAILED AGENT MAP -->\n'+drawing.replace('href="../'+DOCS_DIRNAME+'/','href="'+DOCS_DIRNAME+'/')+'\n<!-- END DETAILED AGENT MAP -->'
    page=re.sub(r'<!-- BEGIN DETAILED AGENT MAP -->.*?<!-- END DETAILED AGENT MAP -->',lambda m:block,page,flags=re.S)
    caps=json.loads((HERE/'memory-capabilities.json').read_text(encoding='utf-8'))['capabilities']
    data=json.dumps({**CATALOG,'exec':{e['id']:('deterministic' if runs_code(e) else 'llm') for e in CATALOG['entities']},'urls':{e['id']:entity_url(e['id']).replace('../'+DOCS_DIRNAME+'/',DOCS_DIRNAME+'/') for e in CATALOG['entities']},'capabilities':[{k:c[k] for k in ('id','kind','one_line','owner','status')} for c in caps]},ensure_ascii=False).replace('<','\\u003c')
    script='<script type="application/json" id="agent-map-catalogue">'+data+'</script>'
    if 'id="agent-map-catalogue"' in page:
        page=re.sub(r'<script type="application/json" id="agent-map-catalogue">.*?</script>',lambda m:script,page,flags=re.S)
    else:page=page.replace('<script src="assets/agent-map.js">',script+'\n<script src="assets/agent-map.js">')
    p.write_text(page,encoding='utf-8')
    inventory();build_catalog_docs();refresh_module_agent_tables()
    print('Built detailed map: four sources and intake; one root stage; 4 working lanes; 31 stages; stage agents with utility agents, consults and gates.')

if __name__=='__main__':build()
