#!/usr/bin/env python3
"""
Apply Crown brand to existing OG SVG templates.

Transforms:
  1. Old indigo/violet gradient colors -> new violet+amber palette
  2. Old "R" corner badge -> mini Crown lockup
  3. "RankWiz" wordmark text -> "RankWizAI"

Run: python3 scripts/branding/update_og_brand.py [--dry-run]
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
PUBLIC = ROOT / "public"

# ---------- Color replacements ------------------------------------------------
# Old palette (from existing templates) -> new Crown palette.
COLOR_MAP = {
    "#6366f1": "#7C3AED",  # indigo-500       -> violet-600 (primary)
    "#8b5cf6": "#5B21B6",  # violet-500       -> violet-800 (band/deep)
    "#c7d2fe": "#DDD6FE",  # indigo-200 text  -> violet-200
    "#1D4ED8": "#7C3AED",  # blue gradient    -> violet
    "#3B82F6": "#5B21B6",  # blue gradient    -> violet-800
    "#22C55E": "#FCD34D",  # green decorative -> amber-300 (rare; sparkle accent)
}

# Match the corner "R" badge block (60x60 rounded rect with 'R' text).
# This block appears at the end of every existing OG SVG.
R_BADGE_PATTERN = re.compile(
    r"""<g\s+transform="translate\(1060,\s*80\)">\s*
        <rect\s+x="0"\s+y="0"\s+width="60"\s+height="60"\s+rx="12"\s+fill="url\(\#accent\)"\s+opacity="0\.9"/>\s*
        <text\s+x="30"\s+y="42"[^>]*>R</text>\s*
    </g>""",
    re.VERBOSE | re.DOTALL,
)

# Mini Crown: on-dark variant. The OG templates use a slate gradient bg with
# a violet decorative circle in the upper-right where this badge sits, so the
# crown silhouette reads as white with amber gems + sparkle accents.
# viewBox 0..120 mapped via scale(0.6) -> 72px wide.
CROWN_BADGE = """<g transform="translate(1060, 80) scale(0.6)">
    <path d="M16 96 L16 76 L28 56 L40 76 L60 36 L80 76 L92 20 L104 76 L104 96 Z" fill="white"/>
    <rect x="16" y="84" width="88" height="12" fill="white" fill-opacity="0.45"/>
    <circle cx="40" cy="80" r="3" fill="#FCD34D"/>
    <circle cx="60" cy="80" r="3" fill="#FCD34D"/>
    <circle cx="80" cy="80" r="3" fill="#FCD34D"/>
    <path d="M92 4 C 93 8 93.5 8.5 97 10 C 93.5 11.5 93 12 92 16 C 91 12 90.5 11.5 87 10 C 90.5 8.5 91 8 92 4 Z" fill="#FCD34D"/>
  </g>"""

# Match the previously-inserted full-color crown badge so we can re-skin it
# without re-running the full transform pipeline.
EXISTING_BADGE_PATTERN = re.compile(
    r'<g\s+transform="translate\(1060,\s*80\)\s+scale\(0\.6\)">[\s\S]*?</g>',
)

# Wordmark: "RankWiz" (standalone, not "RankWizAI") -> "RankWizAI".
# Use word boundary to avoid double-substitution.
WORDMARK_PATTERN = re.compile(r"\bRankWiz\b(?!AI)")
WORDMARK_REPLACEMENT = "RankWizAI"


def transform(content: str) -> str:
    # 1. Colors
    for old, new in COLOR_MAP.items():
        content = content.replace(old, new)
        content = content.replace(old.lower(), new)
        content = content.replace(old.upper(), new)
    # 2a. Original "R" badge -> Crown (first run)
    content = R_BADGE_PATTERN.sub(CROWN_BADGE, content)
    # 2b. Existing crown badge -> latest skin (subsequent runs)
    content = EXISTING_BADGE_PATTERN.sub(CROWN_BADGE, content)
    # 3. Wordmark
    content = WORDMARK_PATTERN.sub(WORDMARK_REPLACEMENT, content)
    return content


def collect_targets() -> list[Path]:
    targets: list[Path] = []
    # Public OG SVGs (skip og-master which is the new clean template)
    for svg in PUBLIC.glob("og-*.svg"):
        if svg.name == "og-master.svg":
            continue
        targets.append(svg)
    # Blog template
    blog_template = PUBLIC / "blog" / "_templates" / "og-base.svg"
    if blog_template.exists():
        targets.append(blog_template)
    # Per-blog-post OG SVGs
    for og in (PUBLIC / "blog").rglob("og.svg"):
        if "_templates" in og.parts:
            continue
        targets.append(og)
    return targets


def main(dry_run: bool = False) -> int:
    targets = collect_targets()
    print(f"Found {len(targets)} OG SVGs to transform")
    changed = 0
    for path in targets:
        original = path.read_text()
        updated = transform(original)
        if updated == original:
            continue
        changed += 1
        if dry_run:
            print(f"  would update: {path.relative_to(ROOT)}")
        else:
            path.write_text(updated)
            print(f"  updated: {path.relative_to(ROOT)}")
    verb = "Would update" if dry_run else "Updated"
    print(f"{verb} {changed} of {len(targets)} files")
    return 0


if __name__ == "__main__":
    sys.exit(main(dry_run="--dry-run" in sys.argv))
