#!/usr/bin/env python3
from __future__ import annotations
import argparse, hashlib, html, importlib.util, json
from pathlib import Path
from typing import Any
from site_navigation import navigation as site_navigation

DEFAULT_OUTPUT = Path('site/regulatory.html')
DEFAULT_SITE_BUILDER = Path('build_site.py')
DEFAULT_CONTENT = Path('regulatory/regulatory_hub_content.json')

SOURCES = {
    'r155_eurlex': 'https://eur-lex.europa.eu/eli/reg/2025/5/oj/eng/pdf',
    'r155_unece': 'https://unece.org/transport/documents/2021/03/standards/un-regulation-no-155-cyber-security-and-cyber-security',
    'r156_unece': 'https://unece.org/transport/documents/2021/03/standards/un-regulation-no-156-software-update-and-software-update',
    'r156_pdf': 'https://unece.org/sites/default/files/2024-03/R156e%20%282%29.pdf',
    'cra_nl': 'https://eur-lex.europa.eu/eli/reg/2024/2847/oj/nld',
    'cra_en': 'https://eur-lex.europa.eu/eli/reg/2024/2847/oj/eng',
    'cra_consolidated': 'https://eur-lex.europa.eu/legal-content/EN/TXT/HTML/?uri=CELEX:02024R2847-20241120',
    'ai_act_nl': 'https://eur-lex.europa.eu/eli/reg/2024/1689/oj/nld',
    'ai_act_en': 'https://eur-lex.europa.eu/eli/reg/2024/1689/oj/eng',
}

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description='Build the NCRC Regulatory hub')
    p.add_argument('--output', type=Path, default=DEFAULT_OUTPUT)
    p.add_argument('--site-builder', type=Path, default=DEFAULT_SITE_BUILDER)
    p.add_argument('--content', type=Path, default=DEFAULT_CONTENT)
    return p.parse_args()

def e(v: Any) -> str:
    return html.escape(str(v or ''), quote=True)

def load_json(path: Path) -> dict[str, Any]:
    with path.open(encoding='utf-8') as f:
        data = json.load(f)
    if not isinstance(data, dict):
        raise ValueError(f'Expected object in {path}')
    return data

def load_site_builder(path: Path):
    spec = importlib.util.spec_from_file_location('ncrc_build_site', path)
    if not spec or not spec.loader:
        raise RuntimeError(f'Cannot load {path}')
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod

def source_button(label: str, url: str) -> str:
    return f'<a class="reg-source" href="{e(url)}" target="_blank" rel="noopener">{e(label)} ↗</a>'

def authority(label: str, kind: str) -> str:
    return f'<span class="reg-authority {e(kind)}">{e(label)}</span>'

def framework_card(fid: str, title: str, subtitle: str, body: str, links: list[tuple[str,str]]) -> str:
    buttons = ''.join(source_button(a,b) for a,b in links)
    return f'''<article class="reg-framework" id="{e(fid)}">
<div class="reg-card-top">{authority('OFFICIAL REGULATION','official')}<span class="reg-code">{e(fid.upper())}</span></div>
<h2>{e(title)}</h2><p class="reg-lead">{e(subtitle)}</p>{body}<div class="reg-sources">{buttons}</div></article>'''

def build_body() -> str:
    r155 = framework_card('r155','UN Regulation No. 155','Vehicle cybersecurity and Cyber Security Management System (CSMS).','''
<p>R155 addresses vehicle cybersecurity through approval requirements, a manufacturer CSMS and vehicle-type cybersecurity measures across development, production and post-production.</p>
<div class="reg-mini-grid"><div><strong>Main regulation</strong><span>Scope, approval, CSMS certification and specifications</span></div><div><strong>Annexes 1–4</strong><span>Information, communication, approval mark and CSMS certificate</span></div><div><strong>Annex 5</strong><span>Threats, vulnerabilities, attack methods and corresponding mitigations</span></div></div>
<p class="reg-note">NCRC threat pages contain the promoted R155 review-baseline traceability. The hub explains the framework and does not duplicate every T-xxx mapping.</p>''', [('Official publication',SOURCES['r155_eurlex']),('UNECE source',SOURCES['r155_unece']),('Threat Register','index.html')])
    r156 = framework_card('r156','UN Regulation No. 156','Software updates and Software Update Management System (SUMS).','''
<p>R156 addresses approval of vehicles with regard to software updates and the organisational processes used to manage those updates.</p>
<div class="reg-mini-grid"><div><strong>SUMS</strong><span>Systematic organisational processes and procedures for software updates</span></div><div><strong>Vehicle requirements</strong><span>Software-update process, integrity, identification and safe execution</span></div><div><strong>Annexes 1–4</strong><span>Information, communication, approval mark and SUMS certificate</span></div></div>
<p class="reg-note">R156 is presented here as a framework overview. Threat-specific R156 traceability is not yet part of the promoted baseline.</p>''', [('UNECE source',SOURCES['r156_unece']),('Official PDF',SOURCES['r156_pdf'])])
    cra = framework_card('cra','EU Cyber Resilience Act','Horizontal cybersecurity requirements for products with digital elements.','''
<p>Regulation (EU) 2024/2847 addresses products with digital elements, essential cybersecurity requirements, vulnerability handling, economic-operator obligations, conformity assessment and market surveillance.</p>
<div class="reg-mini-grid"><div><strong>Product security</strong><span>Design, development and production requirements</span></div><div><strong>Vulnerability handling</strong><span>Processes during the expected period of product use</span></div><div><strong>Scope boundaries</strong><span>Sector-specific exclusions and interaction with other Union rules</span></div></div>
<p class="reg-note">Automotive applicability must be assessed for the specific product and legal context. Expert Views below identify questions, not legal conclusions.</p>''', [('Official text (NL)',SOURCES['cra_nl']),('Official text (EN)',SOURCES['cra_en']),('Consolidated text',SOURCES['cra_consolidated'])])

    zones = '''<section class="card reg-section" id="scope-interaction"><div class="reg-section-head">'''+authority('EXPERT VIEW','expert')+'''<div><p class="section-kicker">Scope interaction</p><h2>Type approval, CRA and the grey zone</h2></div></div>
<p class="muted">This analytical model separates three practical discussion zones. It is not an official legal classification.</p>
<div class="reg-zone-grid">
<article class="reg-zone type"><h3>Type Approved Zone</h3><p>Vehicles and products clearly handled through the applicable type-approval framework and automotive cybersecurity or software-update requirements.</p></article>
<article class="reg-zone cra"><h3>CRA Zone</h3><p>Products with digital elements placed on the EU market that are not covered by an applicable sector-specific exclusion.</p></article>
<article class="reg-zone grey"><h3>Grey Zone</h3><p>Software, hardware, embedded devices and tools whose position between type approval, separate market placement and CRA applicability requires product-specific assessment.</p></article>
</div></section>'''

    ecosystem_items = [
        ('Passenger, commercial vehicles and trailers','Complete vehicles, systems, components and separate technical units in the type-approval context.'),
        ('L-category','Two- and three-wheel vehicles and quadricycles, with category- and timing-specific scope questions.'),
        ('Off-highway and NRMM','Agricultural, forestry and non-road machinery with connected ECUs, telematics, cloud services and software updates.'),
        ('Automotive supply chain','Tier II+, off-the-shelf and out-of-context software and hardware may have less visible assurance in vehicle-level assessments.'),
        ('Software components','Operating systems, middleware, communication stacks, cryptographic libraries and bootloaders.'),
        ('Hardware and embedded units','MCUs, HSMs, secure elements, modems, Wi-Fi/Bluetooth modules, GNSS receivers and advanced sensors.'),
        ('Tools and toolchains','Development, production, diagnostic, calibration, flashing, testing and vulnerability-analysis tools.'),
        ('Outside type approval','EV charging, workshop equipment, aftermarket devices, apps, cloud services and mobility platforms.'),
    ]
    eco=''.join(f'<article class="reg-eco"><h3>{e(a)}</h3><p>{e(b)}</p></article>' for a,b in ecosystem_items)
    ecosystem=f'''<section class="card reg-section" id="ecosystem"><div class="reg-section-head">{authority('EXPERT ANALYSIS','expert')}<div><p class="section-kicker">Automotive ecosystem</p><h2>Where scope questions emerge</h2></div></div><p class="muted">The following areas are retained as structured expert-analysis topics. Each requires verification against the applicable legal and product context.</p><div class="reg-eco-grid">{eco}</div></section>'''

    questions_items = [
        (
            "Automotive supply chain",
            "When does a separately supplied software or hardware component require its own CRA applicability assessment rather than being treated only through vehicle-level type approval?"
        ),
        (
            "Type-approval boundary",
            "Where is the practical boundary between a product covered through vehicle type approval and a product placed independently on the EU market?"
        ),
        (
            "Tools and toolchains",
            "Which development, production, diagnostic and service tools should be assessed independently for CRA applicability?"
        ),
        (
            "Embedded connectivity",
            "How should reusable Wi-Fi, Bluetooth, cellular and GNSS products be treated when the same product is supplied to automotive and non-automotive markets?"
        ),
        (
            "Off-highway and NRMM",
            "How should product-oriented CRA assessment interact with existing vehicle and machinery regulatory regimes in practice?"
        ),
        (
            "Assurance depth",
            "How can cybersecurity assurance remain demonstrable for relevant components originating deeper than the directly assessed automotive supply chain?"
        ),
    ]

    qhtml = "".join(
        f'<article class="reg-question">'
        f'<h3>{e(title)}</h3>'
        f'<p>{e(question)}</p>'
        f'<span class="reg-question-state">OPEN</span>'
        f'</article>'
        for title, question in questions_items
    )

    questions = (
        '<section class="card reg-section" id="open-questions">'
        '<div class="reg-section-head">'
        + authority("OPEN REGULATORY QUESTION", "question")
        + '<div><p class="section-kicker">Open questions</p>'
        '<h2>Questions requiring further validation</h2></div></div>'
        '<p class="muted">'
        'These questions are retained deliberately as unresolved. '
        'They are not presented as legal conclusions and may later be '
        'closed, refined or reclassified when authoritative interpretation '
        'or sufficient review evidence becomes available.'
        '</p>'
        f'<div class="reg-question-grid">{qhtml}</div>'
        '</section>'
    )

    rules='''<section class="card reg-section" id="method"><div class="reg-section-head">'''+authority('NCRC EXPLANATION','ncrc')+'''<div><p class="section-kicker">Method</p><h2>How to read this hub</h2></div></div>
<div class="reg-method-grid"><div><strong>Official regulation</strong><p>Primary or authoritative legal and regulatory sources.</p></div><div><strong>NCRC explanation</strong><p>Neutral orientation and navigation through the frameworks.</p></div><div><strong>Expert View</strong><p>Structured analysis and discussion input, not statutory text or an official interpretation.</p></div><div><strong>Open regulatory question</strong><p>A scope or responsibility question that requires further validation.</p></div></div>
<p class="reg-privacy"><strong>Attribution rule:</strong> individual expert names and affiliations are withheld on the public site. Internal provenance retains the source file, version and authorship.</p></section>'''

    sources='''<section class="card reg-section" id="sources"><div class="reg-section-head">'''+authority('OFFICIAL SOURCES','official')+'''<div><p class="section-kicker">Source access</p><h2>Regulations and annexes</h2></div></div>
<div class="reg-source-list"><div><h3>UN R155</h3><p>Official regulation plus Annexes 1–5.</p>'''+source_button('Open R155',SOURCES['r155_eurlex'])+'''</div><div><h3>UN R156</h3><p>Official regulation plus Annexes 1–4.</p>'''+source_button('Open R156',SOURCES['r156_pdf'])+'''</div><div><h3>Cyber Resilience Act</h3><p>Official Journal text and consolidated documentation version.</p>'''+source_button('Open CRA (NL)',SOURCES['cra_nl'])+source_button('Open consolidated text',SOURCES['cra_consolidated'])+'''</div><div><h3>EU AI Act</h3><p>Regulation (EU) 2024/1689 laying down harmonised rules on artificial intelligence.</p>'''+source_button('Open AI Act (NL)',SOURCES['ai_act_nl'])+source_button('Open AI Act (EN)',SOURCES['ai_act_en'])+'''</div></div></section>'''

    return f'''<section class="reg-hero"><p class="section-kicker">Regulatory knowledge hub</p><h1>Automotive cybersecurity regulation</h1><p class="reg-intro">Official regulations, NCRC explanations, expert analysis and open scope questions are kept visibly separate. The hub connects vehicle type approval, software updates and horizontal product cybersecurity without presenting analysis as legal fact.</p><div class="reg-jumps"><a href="#r155">R155</a><a href="#r156">R156</a><a href="#cra">CRA</a><a href="#scope-interaction">Scope interaction</a><a href="#ecosystem">Ecosystem</a><a href="#sources">Official sources</a></div></section><section class="reg-framework-grid">{r155}{r156}{cra}</section>{zones}{ecosystem}{questions}{rules}{sources}<div class="footer">Regulatory Hub Baseline 1.0 · Expert attribution withheld publicly</div>'''

def main() -> int:
    args=parse_args()
    load_json(args.content)
    site=load_site_builder(args.site_builder)
    extra_css='''
.reg-hero{padding:28px 0 18px}.reg-hero h1{margin:3px 0 8px}.reg-intro{max-width:900px;color:var(--muted);font-size:1.02rem}.reg-jumps{display:flex;gap:7px;flex-wrap:wrap;margin-top:16px}.reg-jumps a,.reg-source{display:inline-flex;padding:7px 10px;border:1px solid var(--line);border-radius:6px;background:var(--surface-alt);color:var(--accent);text-decoration:none;font-size:.78rem;font-weight:700}.reg-jumps a:hover,.reg-source:hover{background:var(--surface-hover);border-color:var(--accent);text-decoration:none}.reg-framework-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-bottom:16px}.reg-framework{padding:18px;border:1px solid var(--line);border-top:4px solid #325d88;border-radius:8px;background:var(--surface)}.reg-framework h2{margin:10px 0 4px}.reg-lead{color:var(--muted);min-height:42px}.reg-card-top,.reg-section-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}.reg-code{font-size:.72rem;color:var(--muted);font-weight:800}.reg-authority{display:inline-flex;padding:4px 7px;border-radius:5px;font-size:.67rem;font-weight:800;letter-spacing:.04em}.reg-authority.official{background:#dce9f5;color:#234b70}.reg-authority.ncrc{background:#e5efe9;color:#285c42}.reg-authority.expert{background:#f3e7d6;color:#7c4d13}.reg-authority.question{background:#eceeef;color:#51565c}.reg-mini-grid{display:grid;gap:7px;margin:12px 0}.reg-mini-grid>div{padding:9px;border:1px solid var(--line);border-radius:6px;background:var(--surface-alt)}.reg-mini-grid strong,.reg-mini-grid span{display:block}.reg-mini-grid span{margin-top:3px;color:var(--muted);font-size:.78rem}.reg-note{font-size:.8rem;color:var(--muted)}.reg-sources{display:flex;gap:6px;flex-wrap:wrap;margin-top:14px}.reg-section{margin-top:16px}.reg-section-head{justify-content:flex-start}.reg-section-head h2{margin:2px 0 0}.reg-zone-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.reg-zone{padding:15px;border:1px solid var(--line);border-radius:7px}.reg-zone.type{border-top:4px solid #8b4c4c}.reg-zone.cra{border-top:4px solid #2c7f9e}.reg-zone.grey{border-top:4px solid #777}.reg-eco-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.reg-eco{padding:13px;border:1px solid var(--line);border-radius:6px;background:var(--surface-alt)}.reg-eco h3{margin:0 0 5px}.reg-eco p{margin:0;color:var(--muted);font-size:.82rem}.reg-method-grid,.reg-source-list{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:9px}.reg-method-grid>div,.reg-source-list>div{padding:13px;border:1px solid var(--line);border-radius:6px;background:var(--surface-alt)}.reg-method-grid p,.reg-source-list p{color:var(--muted);font-size:.8rem}.reg-question-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.reg-question{position:relative;padding:14px 60px 14px 14px;border:1px solid var(--line);border-left:4px solid #777;border-radius:6px;background:var(--surface-alt)}.reg-question h3{margin:0 0 5px}.reg-question p{margin:0;color:var(--muted);font-size:.82rem}.reg-question-state{position:absolute;right:10px;top:10px;padding:3px 6px;border:1px solid #777;border-radius:5px;color:#555;font-size:.64rem;font-weight:800}.reg-privacy{padding:12px;border-left:4px solid #7c4d13;background:var(--surface-alt)}@media(max-width:900px){.reg-framework-grid,.reg-zone-grid{grid-template-columns:1fr}.reg-method-grid,.reg-source-list,.reg-eco-grid{grid-template-columns:1fr 1fr}}@media(max-width:600px){.reg-method-grid,.reg-source-list,.reg-eco-grid,.reg-question-grid{grid-template-columns:1fr}}
'''
    page=site.HEAD.format(title='Regulatory | Automotive Cybersecurity Dashboard', css=site.CSS+extra_css, navigation=site_navigation('Regulatory'))+build_body()+site.TAIL
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(page,encoding='utf-8')
    print(f'Wrote {args.output}')
    return 0
if __name__=='__main__': raise SystemExit(main())
