"""Hreflang article: horizontal bar charts (inline SVG in the blog's chart style) from the pack summary. Writes fig/<lang>-<name>.svg
and fig/<lang>-<name>.figure.html (the <figure> block pasted into the article)."""
import html, json, pathlib

HERE = pathlib.Path(__file__).resolve().parents[2]
_SRC = HERE / 'stage/static/research/hreflang-canonical-2026-11/summary.json'
if not _SRC.exists():  # run from inside the published pack: summary.json sits next to this script
    _SRC = pathlib.Path(__file__).resolve().parent / 'summary.json'
    HERE = _SRC.parent
S = json.loads(_SRC.read_text())
FIG = HERE / 'fig'
N = S['sample']['sites_with_homepage_200']
R = S['return_links']
P = [
    (S['return_links']['sites_with_missing_return_on_some_alt']['sites'], 'r'),
    (S['alternate_status_sites']['sites_with_redirecting_alt']['sites'], 'a'),
    (S['canonical_pages']['sites_missing_selfref']['sites'], 'a'),
    (S['conflict']['sites_with_page_canonical_elsewhere']['sites'], 'r'),
    (S['other']['sites_conflicting_tag']['sites'], 'a'),
    (S['conflict']['sites_with_hreflang_to_non_canonical']['sites'], 'r'),
    (S['other']['sites_relative_url']['sites'], 'a'),
    (S['codes']['sites_with_code_error']['sites'], 'g'),
]
MISS = R['no'] + R['target_lists_only_itself'] + R['target_has_no_hreflang']

STYLE = """    <style>
      .lbl { font: 11px ui-monospace, monospace; fill: rgba(255,255,255,0.62); }
      .ax { font: 10px ui-monospace, monospace; fill: rgba(255,255,255,0.34); }
      .val { font: 10.5px ui-monospace, monospace; fill: rgba(255,255,255,0.55); }
      .grid { stroke: rgba(255,255,255,0.07); }
      .g { fill: #05f29b; opacity: 0.85; }  .a { fill: #f59e0b; opacity: 0.9; }  .r { fill: #f87161; opacity: 0.9; }
    </style>"""


def chart(rows, total, unit, ticks, aria, caption, x0=300, width=290):
    h = 14 + 32 * len(rows) + 30
    mx = ticks[-1]
    out = [f'<svg viewBox="0 0 640 {h}" xmlns="http://www.w3.org/2000/svg">', STYLE]
    for t in ticks:
        x = x0 + width * t / mx
        out.append(f'    <line class="grid" x1="{x:.1f}" y1="14" x2="{x:.1f}" y2="{h - 30}"/>')
        out.append(f'    <text class="ax" x="{x:.1f}" y="{h - 14}" text-anchor="middle">{t}</text>')
    for i, (label, n, cls) in enumerate(rows):
        y = 20 + 32 * i
        w = width * n / mx
        out.append(f'    <rect class="{cls}" x="{x0}" y="{y}" width="{w:.1f}" height="18" rx="2"/>')
        out.append(f'    <text class="lbl" x="{x0 - 12}" y="{y + 13}" text-anchor="end">{html.escape(label)}</text>')
        out.append(f'    <text class="val" x="{x0 + w + 6:.1f}" y="{y + 13}">{n} {unit} {total}</text>')
    out.append('  </svg>')
    svg = '\n'.join(out)
    fig = (f'<figure class="blog-chart" role="img" aria-label="{html.escape(aria)}">\n  {svg}\n'
           f'  <figcaption>{caption}</figcaption>\n</figure>')
    return svg, fig



LBL = {
 'en': ['a language version doesn\'t link back', 'an alternate URL redirects', 'a page doesn\'t list itself',
        'canonical points away from the page', 'one code points to two URLs', 'hreflang points to a non-canonical URL',
        'hreflang uses a relative URL', 'invalid language or region code'],
 'pl': ['wersja językowa nie linkuje zwrotnie', 'adres alternatywny przekierowuje', 'strona nie wskazuje samej siebie',
        'canonical wskazuje inną stronę', 'jeden kod wskazuje dwa adresy', 'hreflang wskazuje adres niekanoniczny',
        'hreflang ma adres względny', 'błędny kod języka lub regionu'],
}
def rows(lang):
    return [(LBL[lang][i], n, c) for i, (n, c) in enumerate(P)]
def aria(lang):
    parts = [f"{l} {n}" for l, n, _ in rows(lang)]
    if lang == 'en':
        return f"Bar chart: how many of {N} multilingual sites had each hreflang problem on at least one checked page: " + ", ".join(parts) + "."
    return f"Wykres słupkowy: ile z {N} wielojęzycznych serwisów miało dany problem z hreflang na co najmniej jednej sprawdzonej stronie: " + ", ".join(parts) + "."
CH = {
 'en': {
  'problems': chart(rows('en'), N, 'of', [0, 4, 8, 12], aria('en'),
     "Sites with each problem on at least one of the pages I checked (10 to 30 per site). Multilingual sites from the Tranco list (top 10k, mid-ranking and .pl), read without JavaScript."),
  'returns': chart([("the alternate doesn't list the page", R['no'], 'r'), ('the alternate lists only itself', R['target_lists_only_itself'], 'r'),
                    ('the alternate has no hreflang at all', R['target_has_no_hreflang'], 'a')], MISS, 'of', [0, 5, 10, 15, 20, 25],
     f"Bar chart: of {MISS} language versions that answered 200 but didn't link back, {R['no']} listed other versions but not the page, {R['target_lists_only_itself']} listed only themselves and {R['target_has_no_hreflang']} had no hreflang at all.",
     "Why a language version didn't link back to the page that pointed to it. Only links from pages whose canonical points to themselves are counted."),
 },
 'pl': {
  'problems': chart(rows('pl'), N, 'z', [0, 4, 8, 12], aria('pl'),
     "Serwisy z danym problemem na co najmniej jednej ze sprawdzonych stron (od 10 do 30 na serwis). Serwisy wielojęzyczne z listy Tranco (top 10 tys., środek rankingu i .pl), odczyt bez JavaScriptu."),
  'returns': chart([('wersja nie wymienia strony', R['no'], 'r'), ('wersja wymienia tylko siebie', R['target_lists_only_itself'], 'r'),
                    ('wersja nie ma hreflang', R['target_has_no_hreflang'], 'a')], MISS, 'z', [0, 5, 10, 15, 20, 25],
     f"Wykres słupkowy: z {MISS} wersji językowych, które odpowiedziały kodem 200, ale nie linkowały zwrotnie, {R['no']} wymieniało inne wersje, ale nie tę stronę, {R['target_lists_only_itself']} wymieniało tylko siebie, a {R['target_has_no_hreflang']} nie miało hreflang wcale.",
     "Dlaczego wersja językowa nie linkowała z powrotem do strony, która na nią wskazała. Liczę tylko linki ze stron, których canonical wskazuje je same."),
 },
}
FIG.mkdir(exist_ok=True)
for lang, charts in CH.items():
    for name, (svg, fig) in charts.items():
        (FIG / f'{lang}-{name}.svg').write_text(svg.replace('<svg ', '<svg style="background:#0b1714" ', 1))
        (FIG / f'{lang}-{name}.figure.html').write_text(fig)
print('ok')
