"""Generate four invented PDF examples and independently check every page.

Run from the project root with --output pointing outside the source package.
This script creates a disposable data store and uses only the local test API.
It does not open a browser or contact any provider.
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import re
import sys
import tempfile
from pypdf import PdfReader
from PIL import Image,ImageDraw
sys.path.insert(0,str(Path(__file__).resolve().parents[1]));sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from backend.app import create_app
from test_boundaries import client,write,job,quote,invoice
from test_documents import doc,act,schedule
from test_websites import read,save,publish
from test_portal_access import enabled,BASE,response


def main():
    parser=argparse.ArgumentParser();parser.add_argument('--output',required=True);parser.add_argument('--report',default='docs/pdf-output-check.json');args=parser.parse_args()
    output=Path(args.output).resolve();output.mkdir(parents=True,exist_ok=True)
    root=Path(__file__).resolve().parents[1];scratch=root.parents[1]/'work';reports=[]
    with tempfile.TemporaryDirectory(prefix='pdf-example-',dir=scratch) as directory:
        app=create_app(Path(directory)/'data');c=client(app)
        pixels=Image.new('RGB',(180,100),'#245648');d=ImageDraw.Draw(pixels);d.rectangle((18,18,66,82),fill='#f8f5e9');d.polygon([(84,82),(115,18),(146,82)],fill='#d0b67e');b=io.BytesIO();pixels.save(b,'PNG')
        r=c.post('/api/assets',content=b.getvalue());assert r.status_code==200;logo=r.json()['id']
        site=read(c)['draft'];site.update(business_name='Vale Demo Workshop',logo_id=logo,address='18 Imaginary Lane\nCwm Dŵr\nExample county',email='hello@valedemo.example');site['document_settings'].update(company_number='FICTIONAL-001',vat_number='DEMO ONLY',payment_terms='Demonstration payment terms only. No real payment is due.');assert save(c,site).status_code==200;assert publish(c).status_code==200
        cfg=c.get('/api/document-settings').json();cfg.update(payment_instructions='For demonstration only: bank Example Bank; reference the saved document number. No real banking details are configured.',quote_acknowledgement_text='I have reviewed the described demonstration work and the stated total.');assert write(c,'/api/document-settings',cfg,method='put').status_code==200
        j=job(c,name='Catrin Dŵr — Llŷn',email='catrin@demo.example')
        payload={'items':[{'description':'Café shelving review — fractional time example','quantity':'0.067','unit_pence':1750},{'description':'Demonstration shelf fitting','quantity':'1.25','unit_pence':2400}], 'vat_percent':20,'notes':'Invented work only.\nWelsh text example: ŵ, ŷ, â, ê, î, ô, û.','valid_until':'2027-01-31'}
        r=write(c,'/api/jobs/'+j['id']+'/quotes',payload);assert r.status_code==200;q=r.json();act(c,'quote',q,'share');p,_,_=enabled(app,c,j)
        output_specs=[]
        output_specs.append(('01-Welsh-Fractional-Quote.pdf',p.get(BASE+'/documents/quote/'+q['id']+'/pdf'),['Catrin Dŵr','£37.40','£1.17','ŵ, ŷ, â, ê, î, ô, û.']))
        assert write(p,BASE+'/quotes/'+q['id']+'/accept',response(c,q,typed_name='Catrin Dŵr')).status_code==200
        inv=act(c,'quote',q,'invoice').json();act(c,'invoice',inv,'issue');stages=schedule(c,inv,amounts=(1122,2618));stage=stages[0]
        path='/api/invoices/'+inv['id']+'/schedule/'+stage['id'];assert write(c,path+'/request',{'version':doc(c,'invoice',inv)['version']}).status_code==200
        assert write(c,'/api/invoices/'+inv['id']+'/payments',{'amount_pence':500,'stage_id':stage['id'],'note':'INTERNAL RECEIPT COMMENT'}).status_code==200
        output_specs.append(('03-Deposit-Request.pdf',p.get(BASE+'/invoices/'+inv['id']+'/schedule/'+stage['id']+'/pdf'),['Payment request','£11.22','£6.22','Not another invoice','£32.40']))
        long_job=job(c,name='Morgan Example — a long fictional household name',email='morgan@demo.example')
        long_items=[{'description':f'Item {n+1:02}: '+('Careful preparation, measured fitting and finishing for this invented room. '*3),'quantity':'1.125','unit_pence':(n+1)*333} for n in range(40)]
        r=write(c,'/api/jobs/'+long_job['id']+'/invoices',{'items':long_items,'vat_percent':5,'notes':('These are invented project terms, retained as saved text across pages. '*22)+'END OF SAVED TERMS','due_date':'2026-11-30'});assert r.status_code==200,r.text;long_inv=r.json();act(c,'invoice',long_inv,'issue')
        output_specs.append(('02-Long-Invoice.pdf',c.get('/api/documents/invoice/'+long_inv['id']+'/pdf'),['Item 01:','Item 40:','END OF SAVED TERMS','Original total']))
        # Change current branding and wording; historical PDF must retain the old logo/content.
        site=read(c)['draft'];site.update(business_name='Later Demo Brand',logo_id=None);save(c,site);publish(c)
        cfg=c.get('/api/document-settings').json();cfg['payment_instructions']='LATER WORDING MUST NOT REPLACE SAVED TEXT';write(c,'/api/document-settings',cfg,method='put')
        output_specs.append(('04-Historical-Invoice.pdf',p.get(BASE+'/documents/invoice/'+inv['id']+'/pdf'),['Vale Demo Workshop','Example Bank','£37.40','£32.40']))
        for filename,result,expected in output_specs:
            assert result.status_code==200,result.text;path=output/filename;path.write_bytes(result.content)
            reader=PdfReader(io.BytesIO(result.content));texts=[page.extract_text() for page in reader.pages];text=' '.join(' '.join(texts).split())
            for phrase in expected:assert phrase in text,(filename,phrase)
            assert 'INTERNAL RECEIPT COMMENT' not in text and 'Later Demo Brand' not in text and 'LATER WORDING MUST NOT' not in text
            assert all('Page '+str(n+1) in value for n,value in enumerate(texts))
            assert all('Local demo' in value for value in texts)
            assert 'Current status summary' in text and 'LOCAL DEMONSTRATION' in text
            reports.append({'file':filename,'pages':len(reader.pages),'sha256':hashlib.sha256(result.content).hexdigest(),'bytes':len(result.content),'text_checks':expected,'all_page_footers_verified':True,'owned_logo_embedded':any(page['/Resources'].get('/XObject') for page in reader.pages)})
        assert doc(c,'invoice',inv)['snapshot']['business']['business_name']=='Vale Demo Workshop'
    report={'version':'0.11.0','independent_extractor':'pypdf 6.10.0','generator':'reportlab 4.4.9','font':'Bundled DejaVu Sans; original licences included','invented_data_only':True,'public_pdf_files':False,'browser_verified':False,'visual_inspection':'pending separate page rendering','examples':sorted(reports,key=lambda r:r['file'])}
    Path(args.report).write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))

if __name__=='__main__':main()
