import json
from pathlib import Path

impact_labels = [
    ('a','Safe operation of vehicle affected'),('b','Vehicle functions stop working'),
    ('c','Software modified, performance altered'),('d','Software altered but no operational effects'),
    ('e','Data integrity breach'),('f','Data confidentiality breach'),
    ('g','Loss of data availability'),('h','Other, including criminality')]

cats = {
'4.3.1':'Threats regarding back-end servers related to vehicles in the field',
'4.3.2':'Threats to vehicles regarding their communication channels',
'4.3.3':'Threats to vehicles regarding their update procedures',
'4.3.4':'Threats to vehicles regarding unintended human actions facilitating a cyber attack',
'4.3.5':'Threats to vehicles regarding their external connectivity and connections',
'4.3.6':'Threats to vehicle data/code',
'4.3.7':'Potential vulnerabilities that could be exploited if not sufficiently protected or hardened',
}
# Normalized labels preserving the regulatory meaning; official reference remains authoritative.
threats = {
'1.1':('4.3.1','Abuse of privileges by staff (insider attack)'),
'1.2':('4.3.1','Unauthorized internet access to the server'),
'1.3':('4.3.1','Unauthorized physical access to the server'),
'2.1':('4.3.1','Attack on back-end server stops it functioning'),
'3.1':('4.3.1','Abuse of privileges by staff (insider attack)'),
'3.2':('4.3.1','Loss of information in the cloud'),
'3.3':('4.3.1','Unauthorized internet access to the server'),
'3.4':('4.3.1','Unauthorized physical access to the server'),
'3.5':('4.3.1','Information breach by unintended sharing of data'),
'4.1':('4.3.2','Spoofing of messages by impersonation'),
'4.2':('4.3.2','Sybil attack'),
'5.1':('4.3.2','Communication channels permit code injection'),
'5.2':('4.3.2','Communication channels permit manipulation of vehicle-held data/code'),
'5.3':('4.3.2','Communication channels permit overwrite of vehicle-held data/code'),
'5.4':('4.3.2','Communication channels permit erasure of vehicle-held data/code'),
'5.5':('4.3.2','Communication channels permit introduction of data/code to vehicle systems'),
'6.1':('4.3.2','Accepting information from an unreliable or untrusted source'),
'6.2':('4.3.2','Man-in-the-middle attack or session hijacking'),
'6.3':('4.3.2','Replay attack'),
'7.1':('4.3.2','Interception of information / interfering radiations / monitoring communications'),
'7.2':('4.3.2','Gaining unauthorized access to files or data'),
'8.1':('4.3.2','Sending a large number of garbage data to vehicle information systems'),
'8.2':('4.3.2','Black hole attack disrupting communication between vehicles'),
'9.1':('4.3.2','An unprivileged user gains privileged access'),
'10.1':('4.3.2','Virus embedded in communication media infects vehicle systems'),
'11.1':('4.3.2','Malicious internal messages, e.g. CAN'),
'11.2':('4.3.2','Malicious V2X messages'),
'11.3':('4.3.2','Malicious diagnostic messages'),
'11.4':('4.3.2','Malicious proprietary messages'),
'12.1':('4.3.3','Compromise of over-the-air software update procedures'),
'12.2':('4.3.3','Compromise of local/physical software update procedures'),
'12.3':('4.3.3','Software manipulated before the update process'),
'12.4':('4.3.3','Compromise of cryptographic keys of the software provider'),
'13.1':('4.3.3','Denial of service against update server or network'),
'15.1':('4.3.4','A legitimate actor is tricked into unintentionally enabling an attack'),
'15.2':('4.3.4','Defined security procedures are not followed'),
'16.1':('4.3.5','Manipulation of functions designed to remotely operate vehicle systems'),
'16.2':('4.3.5','Manipulation of vehicle telematics'),
'16.3':('4.3.5','Interference with short-range wireless systems or sensors'),
'17.1':('4.3.5','Corrupted or insecure hosted third-party applications used to attack vehicle systems'),
'18.1':('4.3.5','External interfaces such as USB or other ports used as a point of attack'),
'18.2':('4.3.5','Virus-infected media connected to the vehicle'),
'18.3':('4.3.5','Diagnostic access used to facilitate an attack'),
'19.1':('4.3.6','Extraction of copyright or proprietary software from vehicle systems'),
'19.2':('4.3.6','Unauthorized access to owner privacy information'),
'19.3':('4.3.6','Extraction of cryptographic keys'),
'20.1':('4.3.6','Illegal or unauthorized changes to vehicle electronic ID'),
'20.2':('4.3.6','Identity fraud'),
'20.3':('4.3.6','Action to circumvent monitoring systems'),
'20.4':('4.3.6','Data manipulation to falsify vehicle driving data'),
'20.5':('4.3.6','Unauthorized changes to system diagnostic data'),
'21.1':('4.3.6','Unauthorized deletion or manipulation of system event logs'),
'22.2':('4.3.6','Introduction of malicious software or malicious software activity'),
'23.1':('4.3.6','Fabrication of software of the vehicle control or information system'),
'24.1':('4.3.6','Denial of service affecting internal vehicle systems or operations'),
'25.1':('4.3.6','Unauthorized changes to configuration parameters of key vehicle functions'),
'25.2':('4.3.6','Unauthorized changes to charging parameters'),
'26.1':('4.3.7','Short encryption keys and long validity enable cryptographic compromise'),
'26.2':('4.3.7','Insufficient use of cryptographic algorithms to protect sensitive systems'),
'26.3':('4.3.7','Use of deprecated or soon-to-be-deprecated cryptographic algorithms'),
'27.1':('4.3.7','Compromised hardware or software parts/supplies enable attack'),
'28.1':('4.3.7','Software bugs create potentially exploitable vulnerabilities'),
'28.2':('4.3.7','Development remnants such as debug ports or credentials enable access or privilege gain'),
'29.1':('4.3.7','Superfluous internet ports left open'),
'29.2':('4.3.7','Circumvention of network separation to gain control'),
'30.1':('4.3.7','Physical damage or theft can cause loss or compromise of sensitive data'),
'30.2':('4.3.7','Loss from digital-rights-management conflicts'),
'30.3':('4.3.7','Sensitive data integrity can be lost due to IT component wear and tear'),
'31.1':('4.3.7','Information breach when a vehicle changes user'),
'32.1':('4.3.7','Physical manipulation or replacement of electronic hardware or sensor inputs'),
}

mit_text = {
'M1':'Back-end security controls minimise insider-attack risk',
'M2':'Back-end security controls minimise unauthorized access',
'M3':'Back-end security controls and recovery measures address critical service outages',
'M4':'Security controls minimise cloud-computing risks',
'M5':'Back-end security controls prevent data breaches',
'M6':'Security by design minimises risk',
'M7':'Access-control techniques and designs protect system data/code',
'M8':'System design and access control prevent unauthorized access to personal or system-critical data',
'M9':'Measures prevent and detect unauthorized access',
'M10':'Vehicle verifies authenticity and integrity of messages it receives',
'M11':'Security controls protect stored cryptographic keys',
'M12':'Confidential data transmitted to or from the vehicle is protected',
'M13':'Measures detect and recover from denial-of-service attacks',
'M14':'Measures protect systems against embedded viruses/malware',
'M15':'Measures detect malicious internal messages or activity',
'M16':'Secure software-update procedures are employed',
'M18':'User roles and access privileges are defined and controlled using least privilege',
'M19':'Organizations define and follow security procedures, including logging of security-management actions/access',
'M20':'Security controls are applied to systems with remote access',
'M21':'Software is security assessed, authenticated and integrity protected; third-party software risk is minimised',
'M22':'Security controls are applied to external interfaces',
'M23':'Cybersecurity best practices are followed for software/hardware development, system design/integration, with appropriate testing',
'M24':'Best practices protect integrity and confidentiality when storing personal data',
}

B = {
'M10':['4.1','5.1','6.1','6.2','11.2'], 'M11':['4.2','12.4'], 'M6':['5.1'],
'M7':['5.2','5.3','5.4','5.5','19.1','20.1','20.3','20.4','20.5','21.1','22.2','23.1','25.1','25.2'],
'M12':['7.1'], 'M8':['7.2'], 'M13':['8.1','8.2','24.1'], 'M9':['9.1','32.1'],
'M14':['10.1'], 'M15':['11.1'], 'M16':['12.1','12.2','12.3'], 'M3':['13.1'],
'M18':['15.1'], 'M19':['15.2'], 'M20':['16.1','16.2','16.3'], 'M21':['17.1'],
'M22':['18.1','18.2','18.3'], 'M8':['7.2','19.2'], 'M11':['4.2','12.4','19.3'],
'M23':['26.1','26.2','26.3','27.1','28.1','28.2','29.1','29.2'], 'M24':['31.1']
}
# Some table rows visually share a mitigation cell. These associations are normalized from that table layout.
C = {
'M1':['1.1','3.1'], 'M2':['1.2','3.3'], 'M8':['1.3','3.4'], 'M3':['2.1'], 'M4':['3.2'], 'M5':['3.5'],
'M18':['15.1'], 'M19':['15.2'], 'M24':['30.1','30.2','30.3']
}

# Fix dictionary overwrite for repeated mitigations by merging intended B associations.
B['M8']=['7.2','19.2']; B['M11']=['4.2','12.4','19.3']

nodes=[]
for ref,(cat,label) in threats.items():
    rel=[]
    for m,refs in B.items():
        if ref in refs: rel.append(f'UN-R155-A5-B-{m}')
    for m,refs in C.items():
        if ref in refs: rel.append(f'UN-R155-A5-C-{m}')
    d={'id':f'UN-R155-A5-A-{ref}','type':'threat_or_vulnerability','part':'A','table':'A1','reference':ref,
       'category_reference':cat,'category_title':cats[cat],'label':label,'related_mitigations':rel}
    if ref in ('4.1','4.2'):
        d['version_state']='amended_by_UN-R155-AMENDMENT-2'
    nodes.append(d)
for part,map_ in [('B',B),('C',C)]:
    for m,refs in map_.items():
        nodes.append({'id':f'UN-R155-A5-{part}-{m}','type':'mitigation','part':part,'reference':m,
                      'domain':'vehicle' if part=='B' else 'outside_vehicle', 'label':mit_text[m],
                      'addresses':[f'UN-R155-A5-A-{r}' for r in refs]})

data={
 'schema_version':'1.1','regulation_id':'UN-R155','annex_id':'UN-R155-ANNEX-5','reference':'Annex 5',
 'title':'List of threats and corresponding mitigations','version_basis':['UN-R155-ORIGINAL','UN-R155-AMENDMENT-2'],
 'source_ids':['UNECE-R155-BASE','UNECE-R155-AMENDMENT-2'],
 'representation':{
   'text_policy':'normalized labels; regulatory reference and official source remain authoritative',
   'ncrc_mappings_embedded':False,
   'amendments_applied':['UN-R155-AMENDMENT-2']
 },
 'parts':[
   {'id':'UN-R155-A5-A','reference':'Part A','title':'Vulnerability or attack method related to the threats','semantic_role':'threat_vulnerability_attack_catalogue'},
   {'id':'UN-R155-A5-B','reference':'Part B','title':'Mitigations to the threats intended for vehicles','semantic_role':'vehicle_mitigations'},
   {'id':'UN-R155-A5-C','reference':'Part C','title':'Mitigations to the threats outside of vehicles','semantic_role':'external_mitigations'}],
 'attack_impacts':[{'reference':r,'label':t} for r,t in impact_labels],
 'categories':[{'reference':r,'title':t} for r,t in cats.items()],
 'nodes':nodes,
 'integrity':{
   'coverage':'full_reference_graph','complete_annex_transcription':False,
   'part_a_reference_count':len(threats),
   'part_b_mitigation_node_count':len(B),
   'part_c_mitigation_node_count':len(C),
   'dangling_addresses':[],
   'future_mapping_file':'../mappings/r155_threat_mappings.json'
 }
}
# validate references
ids={n['id'] for n in nodes}
dang=[]
for n in nodes:
  for k in ('related_mitigations','addresses'):
    for x in n.get(k,[]):
      if x not in ids: dang.append((n['id'],x))
data['integrity']['dangling_addresses']=[{'from':a,'to':b} for a,b in dang]
out=Path('/mnt/data/annex5_full.json')
out.write_text(json.dumps(data,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
print('Part A refs:',len(threats),'B nodes:',len(B),'C nodes:',len(C),'total nodes:',len(nodes),'dangling:',len(dang))
