"""
Rebuild every favicon / app icon / logo / share image from the source images in static/img/.

    python manage.py build_icons

Sources (replace these files, then run the command again):
  static/img/Favicon.png                     – the mark (browser tab + phone icons)
  static/img/The Reverse Times Logo.png      – circular logo (Google's logo for the brand)
  static/img/The reverse Times full logo 1.png – wide wordmark (social share image)
"""
from pathlib import Path

from django.conf import settings
from django.core.management.base import BaseCommand
from PIL import Image, ImageDraw, ImageFont

IMG = Path(settings.BASE_DIR) / 'static' / 'img'
MARK = IMG / 'Favicon.png'
LOGO = IMG / 'The Reverse Times Logo.png'
WORDMARK = IMG / 'The reverse Times full logo 1.png'
DARK = (18, 13, 8)
CREAM = (245, 237, 216)
RED = (227, 64, 31)


def trimmed(path):
    im = Image.open(path).convert('RGBA')
    return im.crop(im.split()[3].getbbox())


def fit(im, size, pad, bg=None):
    """Center `im` on a square canvas, `pad` = fraction of empty margin on each side."""
    canvas = Image.new('RGBA', (size, size), bg + (255,) if bg else (0, 0, 0, 0))
    room = int(size * (1 - 2 * pad))
    scale = min(room / im.width, room / im.height)
    small = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))), Image.LANCZOS)
    canvas.alpha_composite(small, ((size - small.width) // 2, (size - small.height) // 2))
    return canvas


def font(size, bold=False, italic=False):
    names = {(True, False): 'Georgia Bold.ttf', (False, True): 'Georgia Italic.ttf'}.get((bold, italic), 'Georgia.ttf')
    for path in (f'/System/Library/Fonts/Supplemental/{names}', '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf'):
        try:
            return ImageFont.truetype(path, size)
        except OSError:
            continue
    return ImageFont.load_default()


class Command(BaseCommand):
    help = 'Rebuild favicons, app icons, the Google logo and the social share image from static/img sources.'

    def handle(self, *args, **options):
        mark = trimmed(MARK)

        # Browser tab: transparent, mark fills the square
        fit(mark, 256, 0.02).save(IMG / 'favicon.ico', sizes=[(16, 16), (32, 32), (48, 48)])
        fit(mark, 96, 0.02).save(IMG / 'favicon-96.png', optimize=True)
        fit(mark, 48, 0.02).save(IMG / 'favicon-48.png', optimize=True)

        # Phone home screen / installed app: solid background required
        fit(mark, 180, 0.14, DARK).convert('RGB').save(IMG / 'apple-touch-icon.png', optimize=True)
        fit(mark, 192, 0.14, DARK).convert('RGB').save(IMG / 'icon-192.png', optimize=True)
        fit(mark, 512, 0.14, DARK).convert('RGB').save(IMG / 'icon-512.png', optimize=True)

        # Google's brand logo (shown on white): the full circular logo
        fit(trimmed(LOGO), 512, 0.04, (255, 255, 255)).convert('RGB').save(IMG / 'logo-512.png', optimize=True)

        # Social share image 1200×630 (Facebook, WhatsApp, X, LinkedIn)
        og = Image.new('RGBA', (1200, 630), CREAM + (255,))
        word = trimmed(WORDMARK)
        w = 1000
        word = word.resize((w, round(word.height * w / word.width)), Image.LANCZOS)
        og.alpha_composite(word, ((1200 - w) // 2, 210))
        d = ImageDraw.Draw(og)
        d.line((300, 400, 900, 400), fill=RED, width=3)
        line1 = "Bangladesh's first historical magazine"
        f1, f2 = font(44, italic=True), font(30)
        d.text(((1200 - d.textlength(line1, font=f1)) / 2, 425), line1, font=f1, fill=DARK)
        site = 'thereversetimes.com'
        d.text(((1200 - d.textlength(site, font=f2)) / 2, 500), site, font=f2, fill=RED)
        og.convert('RGB').save(IMG / 'og-default.jpg', quality=88)

        self.stdout.write(self.style.SUCCESS('Icons, logo and share image rebuilt in static/img/.'))
