"""Original synthetic plotting examples, not measurement or solver results."""
from pathlib import Path
import argparse
import csv
import hashlib
import json
import shutil
import zipfile
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, FancyArrowPatch
import numpy as np

HERE = Path(__file__).resolve().parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=HERE / 'portfolio')
parser.add_argument('--publish', type=Path, default=None)
options = parser.parse_args()
OUT = options.output.resolve()
PUBLIC = options.publish.resolve() if options.publish else None
OUT.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 10,
    'axes.labelsize': 10, 'axes.titlesize': 11, 'axes.spines.top': False,
    'axes.spines.right': False, 'axes.linewidth': .8, 'svg.fonttype': 'none',
    'svg.hashsalt': 'semiagora-original-services-v1', 'savefig.facecolor': 'white'})
TEAL, ROSE, INK = '#087f8c', '#b24662', '#17252d'
records = []

def data_file(name, columns, rows):
    path = OUT / name
    with path.open('w', newline='', encoding='utf-8') as stream:
        writer = csv.writer(stream)
        writer.writerow(columns)
        writer.writerows(rows)
    return path

def finish(fig, stem, title, caption, source):
    fig.text(.045, .955, title, fontsize=15, fontweight='bold', color=INK)
    fig.text(.045, .035, 'SemiAgora original portfolio | Synthetic illustration - not measured data', fontsize=8, color='#42545e')
    fig.subplots_adjust(top=.82, bottom=.20, left=.095, right=.94, wspace=.36)
    for extension in ['png', 'svg']:
        fig.savefig(OUT / f'{stem}.{extension}', dpi=180,
                    metadata={'Creator': 'SemiAgora original portfolio'})
    plt.close(fig)
    records.append({'id': stem, 'title': title, 'caption': caption,
                    'png': f'{stem}.png', 'svg': f'{stem}.svg', 'data': source,
                    'origin': 'SemiAgora-authored synthetic example',
                    'measurement': False, 'customerWork': False, 'journalAffiliation': False})

vg = np.linspace(0, 1.2, 61)
current = {}
for label, threshold in [('Reference', .42), ('Comparison', .36)]:
    current[label] = .002 + 170 * (.035 * np.logaddexp(0, (vg - threshold) / .035)) ** 2
data_file('transfer-curves.csv', ['gate_voltage_V', 'reference_uA', 'comparison_uA'],
          zip(vg, current['Reference'], current['Comparison']))
fig, axes = plt.subplots(1, 2, figsize=(10, 5.4))
for axis in axes:
    for label, color, marker in [('Reference', TEAL, 'o'), ('Comparison', ROSE, 's')]:
        axis.plot(vg, current[label], label=label, color=color, marker=marker,
                  markevery=8, markersize=4, linewidth=1.7)
    axis.set_xlabel('Gate voltage (V)')
    axis.set_ylabel('Drain current (uA)')
    axis.grid(axis='y', color='#dce3e7', linewidth=.6)
axes[0].set_title('a  Linear scale', loc='left', fontweight='bold')
axes[1].set_title('b  Logarithmic scale', loc='left', fontweight='bold')
axes[1].set_yscale('log')
axes[1].legend(frameon=False, loc='lower right')
finish(fig, 'transfer-panels', 'Device curves | one dataset, two questions',
       'The same 61 synthetic points per condition appear on linear and log axes. No points are removed or altered; neither trace represents a measurement or a fitted compact model.', 'transfer-curves.csv')
fig, ax = plt.subplots(figsize=(10, 5.4))
for label in current:
    ax.plot(vg, current[label], label=label, linewidth=1.4)
ax.set(xlabel='Gate voltage (V)', ylabel='Drain current (uA)', title='Initial single-axis plot')
ax.legend(frameon=False)
finish(fig, 'transfer-initial', 'Initial presentation | identical source points',
       'A valid initial plot of the same data. The revised panels change presentation, not the data.', 'transfer-curves.csv')

cycles = np.arange(0, 141, 5)
thickness_a = .085 * np.maximum(cycles - 8, 0)
thickness_b = .085 * np.maximum(cycles - 24, 0)
data_file('growth-curves.csv', ['cycles', 'illustration_a_nm', 'illustration_b_nm'], zip(cycles, thickness_a, thickness_b))
fig, axes = plt.subplots(1, 2, figsize=(10, 5.4))
ax = axes[0]
ax.set_title('a  Study structure', loc='left', fontweight='bold')
ax.set_axis_off()
for y, label, detail, color in [(.83, 'Surface preparation', 'Define the comparison', TEAL), (.49, 'Thin-film growth', 'Record cycles and conditions', ROSE), (.15, 'Characterization', 'Inspect thickness and variability', '#525e72')]:
    ax.add_patch(Rectangle((.08, y-.10), .84, .20, facecolor='white', edgecolor=color, linewidth=1.4, transform=ax.transAxes))
    ax.text(.5, y+.025, label, ha='center', va='center', transform=ax.transAxes, fontweight='bold', color=color, fontsize=11)
    ax.text(.5, y-.047, detail, ha='center', va='center', transform=ax.transAxes, fontsize=9)
for y in [.72, .38]:
    ax.add_patch(FancyArrowPatch((.5, y), (.5, y-.12), arrowstyle='-|>', mutation_scale=11, color=INK, transform=ax.transAxes))
ax = axes[1]
ax.set_title('b  Illustrative growth response', loc='left', fontweight='bold')
ax.plot(cycles, thickness_a, color=TEAL, marker='o', markersize=3.5, label='Illustration A')
ax.plot(cycles, thickness_b, color=ROSE, marker='s', markersize=3.5, label='Illustration B')
ax.set(xlabel='Deposition cycles', ylabel='Film thickness (nm)')
ax.legend(frameon=False)
ax.grid(axis='y', color='#dce3e7', linewidth=.6)
finish(fig, 'growth-story', 'Process story | connect the workflow to the figure',
       'Original workflow and synthetic delayed-linear growth curves. Chosen slopes and delays are illustrative, not extracted from a paper, a material calibration, an ALD recipe or evidence of a mechanism.', 'growth-curves.csv')

position = np.linspace(0, 1, 51)
x, y = np.meshgrid(position, position)
field = .15 + .8*np.exp(-((x-.58)**2/.055+(y-.42)**2/.075))
data_file('spatial-field.csv', ['x_over_L', 'y_over_L', 'normalized_signal'],
          zip(x.ravel(), y.ravel(), field.ravel()))
fig, axes = plt.subplots(1, 2, figsize=(10, 5.4))
# Half-cell edges keep pixel centres aligned with the CSV sample coordinates.
pixel_extent = (-.01, 1.01, -.01, 1.01)
image = axes[0].imshow(field, origin='lower', extent=pixel_extent, interpolation='nearest', cmap='cividis', vmin=0, vmax=1, aspect='equal')
axes[0].set(xlabel='x / L', ylabel='y / L')
axes[0].set_title('a  Synthetic spatial field', loc='left', fontweight='bold')
fig.colorbar(image, ax=axes[0], fraction=.046, pad=.06, label='Normalized signal')
for row, color, line, marker in [(15, TEAL, '--', 'o'), (25, ROSE, ':', 's')]:
    axes[0].axhline(position[row], color='white', linestyle=line, linewidth=2.7)
    axes[0].axhline(position[row], color=color, linestyle=line, linewidth=1.2)
    axes[1].plot(position, field[row], color=color, linestyle=line, marker=marker,
                 markevery=8, markersize=3.5, label=f'y / L = {position[row]:.2f}')
axes[1].set(xlabel='x / L', ylabel='Normalized signal', ylim=(0, 1))
axes[1].set_title('b  Registered line profiles', loc='left', fontweight='bold')
axes[1].legend(frameon=False)
axes[1].grid(axis='y', color='#dce3e7', linewidth=.6)
finish(fig, 'spatial-evidence', 'Spatial evidence | keep the map and profiles aligned',
       'A 51 by 51 analytic illustration with two registered line profiles. Not a thermal, TCAD, microscopy or wafer measurement result. The colour scale is fixed from 0 to 1.', 'spatial-field.csv')

provenance = {'schema': 'semiagora.service-portfolio.v1', 'synthetic': True,
    'claims': {'measured': False, 'solverExecution': False, 'publishedInJournal': False, 'clientWork': False},
    'parameters': {'transfer': {'points': 61, 'offset_uA': .002, 'gain': 170, 'softness_V': .035, 'thresholds_V': [.42, .36]},
                   'growth': {'step_cycles': 5, 'slope_nm_per_cycle': .085, 'delays_cycles': [8, 24]},
                   'field': {'grid': [51, 51], 'baseline': .15, 'amplitude': .8, 'center': [.58, .42], 'denominators': [.055, .075], 'pixel_extent': list(pixel_extent), 'profile_rows': [15, 25]}},
    'samples': records,
    'rights': 'Original SemiAgora sample text, plots, data and plotting script. No third-party paper figure or data has been imported. Software retains its own license.',
    'journalPolicy': 'Target-journal rules and AI/code assistance disclosure require a separate check; no universal compliance certification.'}
(OUT / 'provenance.json').write_text(json.dumps(provenance, indent=2)+'\n', encoding='utf-8')
(OUT / 'README.txt').write_text('SemiAgora original portfolio\nAll numeric examples are synthetic and labelled, not measured research.\nReproduce: Python with numpy and matplotlib; run build_portfolio.py.\nOriginal data points are unchanged between initial and revised transfer plots.\nNo journal endorsement, customer result, publication guarantee or scientific calibration.\n', encoding='utf-8')
if Path(__file__).resolve() != OUT / 'build_portfolio.py':
    shutil.copy2(__file__, OUT / 'build_portfolio.py')
assets = sorted(path for path in OUT.iterdir() if path.is_file() and path.name not in ['sample-pack.zip', 'asset-manifest.json'])
with zipfile.ZipFile(OUT / 'sample-pack.zip', 'w', compression=zipfile.ZIP_DEFLATED) as archive:
    for path in assets:
        archive.write(path, arcname=path.name)
assets.append(OUT / 'sample-pack.zip')
manifest = [{'name': path.name, 'bytes': path.stat().st_size, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()} for path in assets]
(OUT / 'asset-manifest.json').write_text(json.dumps(manifest, indent=2)+'\n', encoding='utf-8')
if PUBLIC:
    PUBLIC.mkdir(parents=True, exist_ok=True)
    for path in OUT.iterdir():
        if path.is_file() and path.resolve() != (PUBLIC / path.name).resolve():
            shutil.copy2(path, PUBLIC / path.name)
print(json.dumps({'figures': len(records), 'assets': len(manifest), 'sourceRows': [61, 29, 2601], 'synthetic': True, 'public': str(PUBLIC) if PUBLIC else None}, indent=2))
