"""Small terminal selector with an ASCII/number fallback; selection never executes."""
import os
import sys
from field_ui import language


def say(ko, en):
    print(en if language() == 'en' else ko)


def ask(ko, en):
    return input(en if language() == 'en' else ko).strip()


def describe(rows):
    maximum = max([x.get('bytes',0) for x in rows] or [1]) or 1
    for i,r in enumerate(rows,1):
        bar='#'*min(16,round(16*r.get('bytes',0)/maximum))
        print(f"{i:4} [{'!' if r.get('blocked') else 'x'}] {r['kind']:9} {str(r.get('camera','')):8} {r.get('date',''):10} {r.get('bytes',0)/1e9:8.3f}GB {bar:16} {r['id']}")
        if r.get('blocked'):print('     PROTECTED:',r['blocked'])


def choose(rows):
    available={i for i,r in enumerate(rows) if not r.get('blocked')}
    if sys.stdin.isatty() and sys.stdout.isatty() and os.environ.get('TERM','dumb')!='dumb':
        try:
            import curses
            def screen(win):
                selected=set(available);cursor=0
                while True:
                    win.erase();height,width=win.getmaxyx()
                    if height<8 or width<45:raise ValueError('SMALL_TERMINAL')
                    win.addnstr(0,0,'Arrows: move | Space: select | a: all | Enter: preview | q: cancel',width-1)
                    first=max(0,cursor-(height-5)//2)
                    for y,i in enumerate(range(first,min(len(rows),first+height-4)),2):
                        r=rows[i];line=f"[{'!' if i not in available else 'x' if i in selected else ' '}] {r['kind']}/{r.get('camera','')}/{r.get('date','')}/{r['id']} {r.get('bytes',0)/1e9:.3f}GB"
                        win.addnstr(y,0,line,width-1,curses.A_REVERSE if i==cursor else curses.A_NORMAL)
                    win.addnstr(height-1,0,f'Selected {len(selected)} / {len(rows)}; no deletion yet',width-1)
                    key=win.getch()
                    if key in (ord('q'),27):return []
                    if key in (10,13):return [rows[i] for i in sorted(selected)]
                    if key==curses.KEY_DOWN:cursor=min(len(rows)-1,cursor+1)
                    if key==curses.KEY_UP:cursor=max(0,cursor-1)
                    if key==ord('a'):selected=set() if selected==available else set(available)
                    if key==ord(' ') and cursor in available:
                        if cursor in selected:selected.remove(cursor)
                        else:selected.add(cursor)
            if rows:return curses.wrapper(screen)
        except Exception:
            # curses initialization/encoding differs across physical and SSH terminals.
            # This scope selects only; fallback never retries a destructive operation.
            pass
    describe(rows)
    value=ask('번호 쉼표 목록 / all=전체 / Enter=취소: ','Numbers separated by commas / all / Enter=cancel: ')
    if not value:return []
    if value=='all':return [rows[i] for i in sorted(available)]
    selected={int(x.strip())-1 for x in value.split(',')}
    if not selected<=available:raise ValueError('INVALID_OR_PROTECTED_SELECTION')
    return [rows[i] for i in sorted(selected)]
