#!/usr/bin/env python3
"""Chosen source-space point tags with consent, image versions and local HTTP."""
import argparse
import hashlib
import importlib.util
import math
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from PIL import Image, ImageDraw, __version__ as pillow_version

spec=importlib.util.spec_from_file_location('m22_common',Path(__file__).with_name('m22-common.py'))
C=importlib.util.module_from_spec(spec);spec.loader.exec_module(C)
WIDTH,HEIGHT=800,600


def check(condition, message):
    if not condition:
        raise RuntimeError(message)


def finite(value):
    C.require(type(value) in (int,float))
    try:
        C.require(math.isfinite(value))
        return float(value)
    except OverflowError:
        raise C.Refusal(400,'number outside coordinate domain')


def transform(view_width,view_height,fit):
    view_width=finite(view_width);view_height=finite(view_height)
    C.require(1<=view_width<=8192 and 1<=view_height<=8192 and fit in ('contain','cover'))
    scale=(min if fit=='contain' else max)(view_width/WIDTH,view_height/HEIGHT)
    return scale,(view_width-WIDTH*scale)/2,(view_height-HEIGHT*scale)/2


def forward(u,v,w=500,h=500,fit='contain'):
    u=finite(u);v=finite(v);C.require(0<=u<=1 and 0<=v<=1)
    scale,ox,oy=transform(w,h,fit);x=ox+u*WIDTH*scale;y=oy+v*HEIGHT*scale
    return None if x<0 or x>w or y<0 or y>h else (x,y)


def inverse(x,y,w=500,h=500,fit='contain'):
    scale,ox,oy=transform(w,h,fit)
    w=finite(w);h=finite(h);x=finite(x);y=finite(y);C.require(0<=x<=w and 0<=y<=h)
    C.require(ox<=x<=ox+WIDTH*scale and oy<=y<=oy+HEIGHT*scale,400,'outside image')
    u=(x-ox)/(WIDTH*scale);v=(y-oy)/(HEIGHT*scale)
    # Membership is checked in display space above; only quotient roundoff is clipped.
    return min(1.,max(0.,u)),min(1.,max(0.,v))


def make_images(directory):
    directory=Path(directory);directory.mkdir(parents=True,exist_ok=True)
    image=Image.new('RGB',(WIDTH,HEIGHT),'#FBFBFB');draw=ImageDraw.Draw(image)
    draw.rectangle((50,50,750,550),outline='#929292',width=3)
    draw.ellipse((140,90,260,210),fill='#E1E1E1',outline='#272727',width=3)
    draw.rectangle((420,300,620,460),fill='#EFEFEF',outline='#272727',width=3)
    draw.text((20,20),'Chosen geometric source, 800 x 600, orientation 1',fill='#272727')
    source=directory/'m22-photo-source.png';image.save(source)
    overlay=Image.new('RGB',(500,500),'#E1E1E1')
    overlay.paste(image.resize((500,375)),(0,62))
    draw=ImageDraw.Draw(overlay);x,y=forward(.25,.25)
    draw.ellipse((x-7,y-7,x+7,y+7),fill='#272727');draw.text((x+12,y-5),'Bo: chosen point',fill='#272727')
    # Raster preview rounds the 62.5 CSS offset to a row. The mathematical transform remains exact.
    overlay.save(directory/'m22-photo-overlay.png')
    replacement=Image.new('RGB',(WIDTH,HEIGHT),'#FBFBFB');other=ImageDraw.Draw(replacement)
    other.rectangle((100,300,400,500),fill='#E1E1E1',outline='#272727',width=3)
    other.text((20,20),'Chosen replacement image, distinct immutable version',fill='#272727')
    replacement_path=directory/'m22-photo-replacement.png';replacement.save(replacement_path)
    with Image.open(source) as opened:check(opened.size==(WIDTH,HEIGHT), "source dimensions changed")
    return hashlib.sha256(source.read_bytes()).hexdigest(),hashlib.sha256(replacement_path.read_bytes()).hexdigest()


class Tags:
    def __init__(self,path,digest):
        self.path=str(path)
        with C.connect(self.path) as db:
            C.initialize(db)
            db.executescript('''
              CREATE TABLE IF NOT EXISTS images(id TEXT NOT NULL PRIMARY KEY,owner TEXT NOT NULL REFERENCES users(id),current_version INTEGER NOT NULL,
                revision INTEGER NOT NULL,visibility TEXT NOT NULL);
              CREATE TABLE IF NOT EXISTS image_versions(image TEXT NOT NULL REFERENCES images(id),version INTEGER NOT NULL,digest TEXT NOT NULL,
                width INTEGER NOT NULL,height INTEGER NOT NULL,orientation INTEGER NOT NULL,PRIMARY KEY(image,version));
              CREATE TABLE IF NOT EXISTS tags(id INTEGER PRIMARY KEY AUTOINCREMENT,image TEXT NOT NULL,version INTEGER NOT NULL,target TEXT NOT NULL REFERENCES users(id),
                u REAL NOT NULL,v REAL NOT NULL,approved INTEGER NOT NULL,FOREIGN KEY(image,version) REFERENCES image_versions(image,version));
            ''')
            db.execute("INSERT OR IGNORE INTO images VALUES('photo-1','Ada',1,0,'public')")
            db.execute("INSERT OR IGNORE INTO image_versions VALUES('photo-1',1,?,800,600,1)",(digest,))

    def place(self,who,body):
        C.fields(body,['operation','image_version','base_revision','target','u','v'])
        C.text(body['operation'],64);C.text(body['target'],64);C.integer(body['image_version'],1);C.integer(body['base_revision'])
        u,v=finite(body['u']),finite(body['v']);C.require(0<=u<=1 and 0<=v<=1)
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,body['operation'],body)
            if prior is not None:return 200,{**prior,'duplicate':True}
            source=db.execute("SELECT * FROM images WHERE id='photo-1'").fetchone();C.require(source['owner']==who,403,'image owner')
            C.actor(db,body['target']);C.require(source['current_version']==body['image_version'],409,'image version')
            C.require(source['revision']==body['base_revision'],409,'tag revision')
            identifier=db.execute("INSERT INTO tags(image,version,target,u,v,approved) VALUES('photo-1',?,?,?,?,0)",
                                  (body['image_version'],body['target'],u,v)).lastrowid
            db.execute("UPDATE images SET revision=revision+1 WHERE id='photo-1'")
            result={'tag':identifier,'revision':source['revision']+1,'state':'pending'}
            C.remember(db,who,body['operation'],body,result);return 201,{**result,'duplicate':False}

    def consent(self,who,identifier,body):
        C.fields(body,['operation','approved']);C.text(body['operation'],64);C.require(type(body['approved']) is bool)
        intent={'consent_tag':identifier,**body}
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,body['operation'],intent)
            if prior is not None:return 200,{**prior,'duplicate':True}
            row=db.execute('SELECT * FROM tags WHERE id=?',(identifier,)).fetchone();C.require(row is not None,404)
            C.require(row['target']==who,403,'tagged account required')
            source=db.execute('SELECT * FROM images WHERE id=?',(row['image'],)).fetchone()
            C.actor(db,source['owner'])
            C.require(source['visibility']=='public' or source['owner']==who,404,'image unavailable')
            C.require(row['version']==source['current_version'],409,'old image')
            db.execute('UPDATE tags SET approved=? WHERE id=?',(int(body['approved']),identifier))
            result={'approved':body['approved']};C.remember(db,who,body['operation'],intent,result);return 200,{**result,'duplicate':False}

    def read(self,who):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who);source=db.execute("SELECT * FROM images WHERE id='photo-1'").fetchone()
            C.actor(db,source['owner']);C.require(source['visibility']=='public' or source['owner']==who,404,'image unavailable')
            rows=db.execute('SELECT t.id,t.target,t.u,t.v FROM tags t JOIN users u ON u.id=t.target '
                            'WHERE t.image=? AND t.version=? AND t.approved=1 AND u.active=1 ORDER BY t.id',
                            ('photo-1',source['current_version'])).fetchall()
            return {'image_version':source['current_version'],'revision':source['revision'],'tags':[dict(r) for r in rows]}

    def replace(self,digest):
        # Owner-only local source method used by the deterministic replay; no upload endpoint.
        with C.connect(self.path) as db,C.transaction(db):
            C.actor(db,'Ada');version=db.execute("SELECT current_version+1 FROM images WHERE id='photo-1'").fetchone()[0]
            db.execute("INSERT INTO image_versions VALUES('photo-1',?,?,800,600,1)",(version,digest))
            db.execute("UPDATE images SET current_version=?,revision=0 WHERE id='photo-1'",(version,))

    def __call__(self,method,path,who,body):
        if path=='/images/photo-1/tags':
            if method=='POST':return self.place(who,body)
            if method=='GET':return 200,self.read(who)
        if method=='POST' and path.startswith('/tags/') and path.endswith('/consent'):
            middle=path[6:-8];C.require(middle.isascii() and middle.isdigit() and len(middle)<19,404)
            return self.consent(who,int(middle),body)
        raise C.Refusal(404,'route missing')


def main(outdir=None):
    with tempfile.TemporaryDirectory(prefix='m22-photo-') as tmp:
        digest,replacement_digest=make_images(outdir or tmp);print('Pillow='+pillow_version+' source=800x600 orientation=1')
        print('normalized point: u=0.25 v=0.25; source=(200,150)')
        for fit in ('contain','cover'):
            mapped=forward(.25,.25,fit=fit);back=inverse(*mapped,fit=fit)
            error=max(abs(back[0]-.25),abs(back[1]-.25));check(error<=1e-12, "coordinate roundtrip failed")
            print(f'{fit} 500x500: ({mapped[0]:.6f},{mapped[1]:.6f}) roundtrip_error={error:.12f}')
        print('right/bottom equality:',inverse(500,437.5))
        try:inverse(100,20)
        except C.Refusal:print('letterbox click: refused')
        print('cover left-edge source point:',forward(0,.5,fit='cover'))
        service=Tags(Path(tmp)/'tags.sqlite',digest)
        body={'operation':'place1','image_version':1,'base_revision':0,'target':'Bo','u':.25,'v':.25}
        with C.serve(service) as port:
            first=C.request(port,'POST','/images/photo-1/tags',body);print('owner placement:',first[0],first[1]['state'])
            print('identical retry:',C.request(port,'POST','/images/photo-1/tags',body)[0])
            print('changed retry:',C.request(port,'POST','/images/photo-1/tags',{**body,'u':.5})[0])
            print('non-owner placement:',C.request(port,'POST','/images/photo-1/tags',{**body,'operation':'other'},'Cy')[0])
            print('before consent visible tags:',len(C.request(port,'GET','/images/photo-1/tags',who='Dee')[1]['tags']))
            check(C.request(port,'POST','/tags/1/consent',{'operation':'approve1','approved':True},'Bo')[0]==200, 'approval failed')
            print('after Bo consent visible tags:',len(service.read('Dee')['tags']))
            barrier=threading.Barrier(2)
            def change(target):
                barrier.wait();return C.request(port,'POST','/images/photo-1/tags',{**body,'operation':'race-'+target,'base_revision':1,'target':target})[0]
            with ThreadPoolExecutor(2) as pool:statuses=sorted(pool.map(change,['Cy','Eli']))
            print('concurrent revision1:',statuses);check(statuses==[201,409], 'placement conflict missing')
            check(C.request(port,'POST','/tags/1/consent',{'operation':'remove1','approved':False},'Bo')[0]==200, 'withdrawal failed')
            print('consent withdrawn visible tags:',len(service.read('Dee')['tags']))
            print('malformed framing:',C.encoded(C.framing_probes(port,'/images/photo-1/tags',body)))
            with C.connect(service.path) as db:
                check(db.execute('SELECT count(*) FROM tags').fetchone()[0]==2, 'unexpected tag count')
                print('retained tags=2 coordinate pairs=2')
            service.replace(replacement_digest)
            print('replacement visible tags:',len(service.read('Ada')['tags']))
            print('old image placement:',C.request(port,'POST','/images/photo-1/tags',{**body,'operation':'old-image','base_revision':0})[0])
            with C.connect(service.path) as db:db.execute("UPDATE images SET visibility='private' WHERE id='photo-1'")
            print('private image read:',C.request(port,'GET','/images/photo-1/tags',who='Bo')[0])


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--images');main(parser.parse_args().images)
