"""Reproduce a six-row transcription and charts of published Table 4.

Requires Python 3 and matplotlib. Run from any working directory.
Data: Malopheyev et al. (2020), DOI 10.3390/ma13194246, CC BY 4.0.
This script does not fit data, simulate welding, or infer significance.
"""
from pathlib import Path
import csv
import json
import xml.etree.ElementTree as ET
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
PROPERTIES = [
    ('Yield strength', 'MPa', (316, 283), (3, 7), 380),
    ('Ultimate tensile strength', 'MPa', (362, 311), (1, 12), 430),
    ('Elongation to failure', '%', (9, 3), (1, 1), 12),
]
CONDITIONS = ('Base material', 'Welded joint (post-weld aged)')
SOURCE = 'https://pmc.ncbi.nlm.nih.gov/articles/PMC7579519/'
ATTRIBUTION = 'Adapted from Malopheyev et al. (2020), Table 4. DOI: 10.3390/ma13194246. CC BY 4.0.'
DESC = ('6061 alloy, initially T6-tempered. Base versus post-weld-aged friction-stir joint. '
        'Yield strength: 316 plus or minus 3 versus 283 plus or minus 7 MPa. '
        'Ultimate tensile strength: 362 plus or minus 1 versus 311 plus or minus 12 MPa. '
        'Elongation to failure: 9 plus or minus 1 versus 3 plus or minus 1 percent. '
        'Reported plus-minus statistic is undefined; at least two specimens per condition. '
        'These values do not establish significance, equivalence, or service safety.')

def main():
    with (ROOT / 'joining-properties.csv').open('w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['property', 'condition', 'value', 'reported_plusminus', 'unit'])
        for name, unit, values, errors, _ in PROPERTIES:
            for condition, value, error in zip(CONDITIONS, values, errors):
                writer.writerow([name, condition, value, error, unit])
    methods = {
        'title': 'Measured properties before and after joining: one 6061 study',
        'source': {'authors': ['Sergey Malopheyev', 'Igor Vysotskiy', 'Daria Zhemchuzhnikova', 'Sergey Mironov', 'Rustam Kaibyshev'],
                   'title': 'On the Fatigue Performance of Friction-Stir Welded Aluminum Alloys',
                   'year': 2020, 'doi': '10.3390/ma13194246', 'url': SOURCE,
                   'locator': 'Table 4; sections 2.1, 2.2, 2.5 and 3.2',
                   'license': 'CC BY 4.0', 'license_url': 'https://creativecommons.org/licenses/by/4.0/',
                   'attribution': ATTRIBUTION},
        'material': '6061 aluminium alloy, initially extruded and T6-tempered',
        'joint_condition': 'Double-sided friction-stir joint; artificial ageing after welding',
        'test': {'type': 'Static transverse tensile test to failure', 'temperature': 'ambient',
                 'nominal_strain_rate_per_second': 0.001,
                 'specimens_per_condition': 'at least two; exact number unspecified',
                 'joint_fracture_location': 'heat-affected zone'},
        'uncertainty': 'Transcribed reported plus-minus values; statistic undefined in inspected text. Do not label SD, SE, or confidence intervals.',
        'transforms': ['Verbatim numerical transcription into six rows', 'Separate panels retain original units',
                       'Derived central-value ratio = 100 * joint value / base value; no uncertainty propagated'],
        'central_value_ratios_percent': {name: 100 * values[1] / values[0] for name, _, values, _, _ in PROPERTIES},
        'limits': ['Not a simulation', 'No statistical significance or equivalence inference',
                   'No generalisation to all alloys or joining methods',
                   'No inference about corrosion, fatigue or service safety from this table',
                   'No fabrication or process optimisation instructions'],
        'accessibility': {'svg_role': 'img', 'svg_title_and_description': True, 'description': DESC,
                          'note': 'HTML integration should provide the CSV values as a native accessible table; PDFs are visual charts, not tagged-PDF accessibility certification.'},
        'outputs': ['joining-properties.csv', 'joining-properties.svg', 'joining-properties.pdf',
                    'joining-properties-mobile.svg', 'joining-properties-mobile.pdf'],
    }
    (ROOT / 'methods.json').write_text(json.dumps(methods, indent=2) + '\n', encoding='utf-8')
    plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 11, 'svg.fonttype': 'none',
                         'axes.spines.top': False, 'axes.spines.right': False})
    for mobile in (False, True):
        fig, axes = plt.subplots(3 if mobile else 1, 1 if mobile else 3,
                                 figsize=(5.2, 11.5) if mobile else (13.5, 5.8))
        fig.subplots_adjust(left=.18 if mobile else .07, right=.96, bottom=.18 if mobile else .29,
                            top=.85 if mobile else .70, hspace=.65, wspace=.42)
        fig.suptitle('Joining changes different properties\nby different amounts', y=.98, fontsize=17, fontweight='bold')
        fig.text(.5, .925 if mobile else .855,
                 '6061 alloy: initially T6-tempered\nJoint tested after post-weld artificial ageing',
                 ha='center', va='top', fontsize=11)
        for ax, (name, unit, values, errors, upper) in zip(axes.flat, PROPERTIES):
            ax.bar([0, 1], values, width=.55, color=['#23607c', '#bf5b32'],
                   edgecolor='#172b38', linewidth=.7, yerr=errors,
                   error_kw={'capsize': 6, 'ecolor': '#172b38', 'elinewidth': 1.5})
            ax.set_xticks([0, 1], ['Base\nmaterial', 'Joint\n(post-weld aged)'])
            ax.set_ylabel(unit)
            ax.set_title(name, fontsize=12, pad=12)
            ax.set_ylim(0, upper)
            ax.yaxis.grid(True, alpha=.2)
            ax.set_axisbelow(True)
            for x, v, e in zip([0, 1], values, errors):
                ax.text(x, v + e + upper*.035, f'{v} ± {e}', ha='center', fontsize=11)
        footer = ('Error bars: reported ±; statistic undefined.\nAt least 2 specimens per condition; exact n unspecified.\n'
                  'Descriptive comparison only; no significance or equivalence claim.\n'
                  'Adapted from Malopheyev et al. (2020), Table 4.\nDOI: 10.3390/ma13194246 | CC BY 4.0')
        if mobile:
            footer = footer.replace('Descriptive comparison only; no significance or equivalence claim.',
                                    'Descriptive comparison only.\nNo significance or equivalence claim.')
        fig.text(.05, .025 if mobile else .035, footer, fontsize=9.5, linespacing=1.5, va='bottom')
        stem = 'joining-properties' + ('-mobile' if mobile else '')
        fig.savefig(ROOT / f'{stem}.pdf', metadata={'Title': '6061 joining: measured property comparison',
                                                   'Author': 'DMGB educational adaptation; data Malopheyev et al.',
                                                   'Subject': DESC})
        fig.savefig(ROOT / f'{stem}.svg')
        fig.savefig(ROOT / f'{stem}-preview.png', dpi=120)
        plt.close(fig)
        svg_path = ROOT / f'{stem}.svg'
        svg = ET.parse(svg_path)
        root = svg.getroot()
        ns = '{http://www.w3.org/2000/svg}'
        root.set('role', 'img')
        root.set('aria-labelledby', 'chart-title chart-description')
        title = ET.Element(ns + 'title', {'id': 'chart-title'})
        title.text = 'Measured properties of 6061 base material and post-weld-aged joint'
        description = ET.Element(ns + 'desc', {'id': 'chart-description'})
        description.text = DESC + ' ' + ATTRIBUTION
        root.insert(0, title)
        root.insert(1, description)
        ET.register_namespace('', 'http://www.w3.org/2000/svg')
        svg.write(svg_path, encoding='utf-8', xml_declaration=True)
    assert sum(1 for _ in (ROOT / 'joining-properties.csv').open(encoding='utf-8')) == 7
    print('Created six-row CSV, methods, two SVGs, two PDFs, and preview PNGs.')

if __name__ == '__main__':
    main()
