"""HUD bag glyph + surrounding capacity ring, never arbitrary red pixels."""
from functools import lru_cache
import cv2
import numpy as np
from PIL import Image
from ..paths import resource_dir
from ..catalog import normalized

NOTICE_BOTTOM = (.34, .78, .70, .92)


def bag_warning(obs):
    phrases = ('가방이가득', '가방무게가초과', '가방의무게가초과',
               '소지무게를초과', '소지무게가초과', '가방공간이부족',
               '가방이무거워채집', '가방이가득차서채집')
    for t in obs.texts:
        x,y=t.center[0]/obs.width,t.center[1]/obs.height
        if t.score>=.90 and .2<=x<=.85 and (.07<=y<=.32 or .78<=y<=.94):
            if any(p in normalized(t.text) for p in phrases):return t.text
    return None  # "아이템이 많아 무거워졌다" is an early warning, not full.


@lru_cache(maxsize=2)
def _glyph(full=False):
    name='bag-capacity-full-glyph.png' if full else 'bag-capacity-glyph.png'
    with Image.open(resource_dir()/'combat-anchors'/name) as im:
        return np.asarray(im.convert('L'))


def bag_capacity(image, obs):
    """True=red full ring, False=orange/yellow ring, None=unmeasured/hidden."""
    if image is None or not 1.74<=obs.width/obs.height<=1.82:return None
    if image.size!=(obs.width,obs.height) or obs.width<640:return None
    if not any(normalized(t.text) in ('퀘스트','퀘스트+','퀘스트＋') and
               t.score>=.7 and t.center[0]>obs.width*.7 for t in obs.texts):return None
    w,h=image.size
    x0,y0,x1,y1=round(w*.86),round(h*.89),round(w*.923),round(h*.984)
    rgb=np.asarray(image.crop((x0,y0,x1,y1)).convert('RGB'))
    scale=w/3840
    matches=[]
    for full in (False,True):
        glyph=cv2.resize(_glyph(full),None,fx=scale,fy=scale,interpolation=cv2.INTER_AREA)
        if min(glyph.shape)<2 or any(a<b for a,b in zip(rgb.shape[:2],glyph.shape)):return None
        scores=cv2.matchTemplate(cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY),glyph,cv2.TM_CCOEFF_NORMED)
        _,score,_,point=cv2.minMaxLoc(scores)
        matches.append((score,point))
    score,point=max(matches)
    if score<.82:return None
    # Reference glyph box (3380,1972,3454,2048); ring centre (3420,2020).
    cx,cy=point[0]+40*scale,point[1]+48*scale
    yy,xx=np.indices(rgb.shape[:2]);radius=np.hypot(xx-cx,yy-cy)/scale
    ring=(radius>=65)&(radius<=81)
    hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
    vivid=ring&(hsv[:,:,1]>140)&(hsv[:,:,2]>130)
    if vivid.sum()<ring.sum()*.20:return None
    red=vivid&((hsv[:,:,0]<10)|(hsv[:,:,0]>173))
    amber=vivid&(hsv[:,:,0]>=12)&(hsv[:,:,0]<40)
    if red.sum()>vivid.sum()*.65:return True
    if amber.sum()>vivid.sum()*.65:return False
    return None
