from pathlib import Path
import json, math, csv, hashlib, shutil, html, io
from PIL import Image, ImageDraw, ImageFont, ImageOps
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor, Color
from reportlab.lib.utils import ImageReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle

ROOT = Path('/workspace/scratch/a4f3a793eeef')
B = ROOT/'MVPCS_Evidence'
M = B/'01_Maps_and_Imagery'
H = B/'04_Historical_Context'
C = B/'05_Research_Catalog'
V = B/'06_Visual_Plates'
V.mkdir(exist_ok=True)
DATE = '23 September 2026'
NAVY = '#102f3b'; TEAL = '#007e88'; PAPER = '#f6f4ef'; GOLD = '#ffce69'; CYAN = '#4de8ef'
FONT = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
BOLD = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
pdfmetrics.registerFont(TTFont('DV', FONT)); pdfmetrics.registerFont(TTFont('DVB', BOLD))

bad = H/'Whiting_historic_landscape.jpeg'
if bad.exists(): shutil.move(str(bad),str(ROOT/'work/Whiting_unrelated_southshore.jpeg'))
parcels = json.loads((M/'MVPCS_parcels_FY2026.geojson').read_text())
bbox = json.loads((C/'map_extent.json').read_text())['bbox']
imagery = json.loads((C/'imagery_acquisition.json').read_text())
sat = json.loads((C/'satellite_source.json').read_text())
catalog=[]
def add(id,title,date,scope,files,url,notes,rights='See source metadata',status='Acquired'):
    row=dict(id=id,title=title,date=date,scope=scope,files=files,url=url,notes=notes,rights=rights,status=status,accessed='2026-09-23')
    catalog.append(row); return row
def rel(path): return str(Path(path).relative_to(B))
masscredit='MassGIS (Bureau of Geographic Information), Commonwealth of Massachusetts EOTSS'
parcelurl='https://services1.arcgis.com/hGdibHYSPO59RG1h/arcgis/rest/services/Massachusetts_Property_Tax_Parcels/FeatureServer/0'
add('P01','Current assessor parcels: 420 and 424 State Road','FY2026','Exact tract',[rel(M/'MVPCS_parcels_FY2026.geojson')],parcelurl,
    'Town 327. Parcels 16-96 and 16-96-3, owner Options in Education Inc. Assessor geometry is not a legal survey. Both cite one deed: Book 675, page 665, 29 April 1996, $240,000. Reported lot areas sum to 316,245 sq ft (7.26 acres).',masscredit)
registryurl='https://www.masslandrecords.com/Dukes/'
add('P02','1996 acquisition deed: registry index and document details','1996-04-29','Exact tract',
    ['02_Public_Records/MVPCS_1996_deed_index.jpg','02_Public_Records/MVPCS_1996_deed_index.txt'],registryurl,
    'Book 675/page 665; document 2683; two pages; $240,000. Grantors indexed as Cournoyer Mary E TRS and Middletown Village Trust; grantee Options in Education Inc. Easement reference 682/724. This is an index screenshot, NOT the deed instrument or a survey. Viewer failed; full deed scan was not acquired.',
    'Public registry record; interface © Avenu Insights & Analytics. Screenshot retained as research evidence.')
for a in imagery:
    if not a.get('file'): continue
    date=a['date_label'].replace('_','–')
    notes='Georeferenced tile mosaic at zoom 18, 914 × 914 pixels. Unmarked original and derived parcel overlay supplied. Same extent for all nine dates. '
    notes+=a.get('date_basis','Dataset year or year range; an exact local flight day was not established.')
    add('A'+a['date_label'],date+' aerial orthophotography',date,'Exact tract',[rel(M/a['file']),rel(M/Path(a['file']).with_suffix('.jgw'))],a['url'],notes,masscredit+'; public MassGIS imagery, subject to source metadata.')
add('A-DATE','MassGIS flight-status map establishes the Vineyard image year as 1999','2000-04-13','Date verification',
    ['04_Historical_Context/1990s_flight_status.pdf','06_Visual_Plates/1999_aerial_date_evidence.png'],
    'https://www.mass.gov/doc/stoqpdf/download','Vineyard coverage is colored for 1999; the service name alone says only 1990s.',masscredit)
add('A-2003-DATE','MassGIS 2001/2003 imagery metadata','2003','Date verification',[],
    'https://www.mass.gov/info-details/massgis-data-2001-2003-aerial-imagery',
    'The metadata specifies April 2003 photography for the islands. The service name is orthos_2001_tile_package. Collection filenames use the island acquisition year, 2003.',masscredit,'Reference / metadata checked')
add('S01','Sentinel-2 cloudless annual satellite mosaic','2024','Vicinity',[rel(M/'Sentinel2_2024_regional_satellite.jpg')],sat['url'],
    'Regional satellite context, about 3 km across on the ground. Annual mosaic, not one exposure or a live image. Approximately 10 m source pixels; WMS display pixels are smaller. '+sat['credit'],
    sat['credit']+'; CC BY-NC-SA 4.0, https://creativecommons.org/licenses/by-nc-sa/4.0/')
topos=[('1951','USGS_Vineyard_Haven_1951_printed1952.pdf',
    'https://prd-tnm.s3.amazonaws.com/StagedProducts/Maps/HistoricalTopo/PDF/MA/31680/MA_Vineyard%20Haven_463101_1951_31680_geo.pdf',
    'Surveyed 1942; revised 1951; the USGS record identifies a 1952 print. Scale 1:31,680. This edition does not show forest shading: white ground must not be read as cleared land.'),
    ('1972','USGS_Vineyard_Haven_1972_25000.pdf',
    'https://prd-tnm.s3.amazonaws.com/StagedProducts/Maps/HistoricalTopo/PDF/MA/25000/MA_Vineyard%20Haven_351378_1972_25000_geo.pdf',
    'Planimetry from 1939 aerials and 1942 field work; revised from 1969 aerial photographs; field checked 1972. Scale 1:25,000. Green woodland tint crosses the current school parcels. Map scale and labels limit interpretation of individual small structures.')]
for year,fn,url,notes in topos:
    add('T'+year,'USGS Vineyard Haven quadrangle',year,'Exact tract / vicinity',
        [rel(M/fn),rel(M/f'USGS_{year}_school_vicinity_unmarked.jpg'),rel(V/f'USGS_{year}_school_vicinity_overlay.jpg')],url,
        notes+' Magenta parcel overlay is a modern reconstruction from FY2026 geometry, not a historical boundary or surveyed alignment. Full original geospatial PDF included.','USGS; United States government work, public domain.')
arc=json.loads((C/'archive_acquisition.json').read_text())
for id in dict.fromkeys(a['id'] for a in arc):
    rows=[a for a in arc if a['id']==id]
    meta=json.loads((C/f'DC_{id}_metadata.json').read_text())
    extra={
        '25152j880':'A town plan from before West Tisbury separated from Tisbury in 1892. Broad location context; no parcel-level georeferencing performed.',
        '79408315w':'Island map and historic road geography. Does not establish the owner or use of the exact modern school lots.',
        '7h149z539':'Eastern Vineyard / Nantucket chart. Regional coastal context only; its coverage and scale do not resolve the school tract.',
        'c821mx42g':'All four scans acquired. Community correspondence relating to Christiantown and Chappaquiddick, not a conveyance of the school parcel.',
        '0p09bk77g':'All six scans acquired. A community property inventory for Christiantown and Chappaquiddick, listing household dwellings, improved land, woodland and livestock. The word estate refers to property here; this is not a will or an established decedent probate inventory. It has not been linked to the school title chain.',
        '7366dr72r':'All sixteen scans acquired. Government report about Christiantown; not proof that the present school tract belonged to or was used by a particular person.',
        'pc28bt615':'Unaltered regional oblique aerial, North Tisbury to Seven Gates Farm. The school footprint has not been located in this photograph. Attribution: David R. Foster, Harvard University.',
        'z890s049v':'Nearby Christiantown chapel, not a prior building on the school site. Date range follows the repository catalog, circa 1890–1940. Photographer Edward Lee Luce; Martha’s Vineyard Museum.'
    }[id]
    add('D'+id,rows[0]['title'], '; '.join(meta.get('date_tsim',[])),'Regional / nearby context',
        [rel(H/a['file']) for a in rows],rows[0]['source'],extra,
        ' / '.join(str(meta.get(k,'')) for k in ['rights_ss','license_ss','license_uri_ss'] if meta.get(k)))
hfbase='https://harvardforest.fas.harvard.edu/'
maps=[
 ('H1698','Simon Athearn map of Martha’s Vineyard','1698','1698_Simon_Athearn_Vineyard_Map.jpg','wp-content/uploads/2025/05/1698_Simon_Athearn_Marthas_Vineyard_1698_001full.jpg','Photographic reproduction; modern caption below the image cropped out. Glare and limited resolution are inherited from the reproduction.'),
 ('H1781','Des Barres: Buzzards Bay and western Martha’s Vineyard','1781','1781_DesBarres_Western_Vineyard.jpg','wp-content/uploads/2025/05/1781_Des_Barres_Buzzards_Bay_Western_Marthas_Vineyard_small.jpg','Small reproduction. Useful for regional landform and coastal context; no exact school-site claim.'),
 ('H1850','Henry Laurens Whiting landscape map reproduction','circa 1850','Whiting_1850_map.jpg','wp-content/uploads/2025/04/1850map.jpg','Hosted reproduction associated with Whiting’s mid-nineteenth-century surveys. The source discusses surveys of 1844–1852 and a later chart. Do not treat the file label as an exact date for every mapped feature.'),
 ('H1858','Walling map of Barnstable, Dukes and Nantucket counties','1858','1858_Walling_County_Map.jpg','wp-content/uploads/2025/05/1858_Walling_Barnstable_Dukes_and_Nantucket_Counties_small.jpg','Low-resolution regional reproduction. Too coarse to establish a building or ownership at the school footprint.')]
for id,title,date,fn,url,note in maps:
    add(id,title,date,'Regional context',[rel(H/fn)],hfbase+url,note+' Historical original is old enough to be public domain; acknowledge Harvard Forest as the reproduction source.', 'Historical map reproduction supplied by Harvard Forest; no separate image license stated on the retrieved page.')

news=[
 ('N1995','New Charter School Makes Progress','1995-12-08','https://vineyardgazette.com/news/1995/12/08/new-charter-school-makes-progress','Contemporary report: the organizers were still looking for a location after examining about 25 possibilities.'),
 ('N1996a','Vineyard Public Charter School Opens Admissions for Fall Term','1996-02-09','https://vineyardgazette.com/news/1996/02/09/vineyard-public-charter-school-opens-admissions-fall-term','Reports selection of a State Road site near Indian Hill and Lambert’s Cove, with modular classrooms planned.'),
 ('N1996b','Public Charter School Is Days Away from Island Launch','1996-09-06','https://vineyardgazette.com/news/1996/09/06/public-charter-school-days-away-island-launch','Describes new school construction in wooded surroundings: a post-and-beam central area and four portable classrooms. Headline/byline/date screenshot included; article text remains at the publisher.'),
 ('N1997','Island Public Charter School Wins Permission for Expansion','1997-07-25','https://vineyardgazette.com/news/1997/07/25/island-public-charter-school-wins-permission-expansion','Reports permission for a 36-by-32-foot classroom addition.'),
 ('N2009','Charter School Cuts Ribbon on Four Brand New Classrooms','2009-09-17','https://vineyardgazette.com/news/2009/09/17/charter-school-cuts-ribbon-four-brand-new-classrooms','Reports a roughly 3,500-square-foot addition with four elementary classrooms and supporting spaces.')]
for id,title,date,url,note in news:
    files=['03_Newspaper_References/MVPCS_Gazette_1996_09_06_headline.jpg'] if id=='N1996b' else []
    add(id,title,date,'Exact tract',files,url,note,'Vineyard Gazette; article copyright retained by publisher. Short reference and paraphrase only.', 'Headline screenshot + reference' if files else 'Reference / article checked')

references=[
 ('R-SCHOOL','MVPCS school history','1996 / retrospective','Exact tract','https://mvpcs.org/?p=250','School account gives opening date as 16 September 1996.'),
 ('R-OIE','Options in Education: organizational history','Retrospective','Exact tract','https://www.mvoptionsineducation.org/about-oie','Retrospective account places land/construction activity in 1995. The dated 1996 deed, assessor year-built field, and contemporary newspaper reports support 1996 for acquisition and opening; retain the discrepancy rather than silently combine the dates.'),
 ('R-TOWN','West Tisbury town history','1671 / 1892','Regional context','https://www.westtisbury-ma.gov/about_west_tisbury/history.php','Tisbury dates to 1671; West Tisbury became a separate town in 1892. Earlier records may therefore be under Tisbury.'),
 ('R-TRIBE','Wampanoag Tribe of Gay Head (Aquinnah): history','Deep history / present','Regional context','https://wampanoagtribe-nsn.gov/wampanoag-history','Tribal account describes at least 10,000 years of Wampanoag presence on Noepe. This is Island-wide history, not archaeological evidence excavated from the school parcel.'),
 ('R-CHRIST','Christiantown Woods Preserve','1659 / later','Nearby context','https://www.mvlandbank.com/properties/christiantown-woods-preserve','Land Bank history places the neighboring Christiantown community in a seventeenth-century setting. No historical reservation boundary has been matched to the school lots in this collection.'),
 ('R-HF','Harvard Forest historical maps collection','1698–1901','Regional context',hfbase+'education-opportunities/classic-outreach-resources/marthas-vineyard/historical-maps/','Repository page for the Athearn, Des Barres, Whiting and Walling reproductions.'),
 ('R-WHITING','Harvard Forest: Whiting’s landscape map','1844–1860','Regional context',hfbase+'education-opportunities/classic-outreach-resources/marthas-vineyard/1850-map-henry-laurens-whiting/','Explains Whiting survey history and the landscape reconstruction. The reproduction in this cache is not sufficiently georeferenced for a parcel-level land-use assertion.'),
 ('R-MVM','Martha’s Vineyard Museum maps collection index','Various','Unverified leads','https://mvmuseum.org/wp-content/uploads/2019/06/Maps_Collection_Index.pdf','Catalog leads: 1985 assessor map 2012.035.017; 1895 West Tisbury Road 2012.035.033; 1896 Middletown Road 2012.035.027; circa-1900 Quannowill/Mingo Christiantown map 2012.035.014 and annotations 2012.035.013; Banks reconstruction of Christiantown in 1709, 2012.035.012. Images not acquired, and overlap with the exact school land is unverified.'),
 ('R-TISBURY','Tisbury town records finding aid','1669–1927','Unverified leads','https://mvmuseum.org/EAD_FindingAids/findingaid_get.php?record-unit=RU505','Potential route to early town land divisions. No document from this collection was matched to the school tract in this research.'),
 ('R-MVC2004','Martha’s Vineyard Commission minutes','2004-04-15','Exact tract / reference','https://www.mvcommission.org/sites/default/files/docs/2004-04-15%20MVC%20Minutes.pdf','Indexed text describes DRI 423-M5, a 750-square-foot addition and kindergarten trailer removal. Original PDF download denied (HTTP 403); not in cache.'),
 ('R-MVC2008','Martha’s Vineyard Commission minutes','2008-06-12','Exact tract / reference','https://www.mvcommission.org/sites/default/files/docs/Commission_2008_06_12.pdf','Relevant school expansion record identified; PDF download denied (HTTP 403). Not in cache.'),
 ('R-MVC2014','Martha’s Vineyard Commission minutes','2014-05-08','Exact tract / reference','https://www.mvcommission.org/sites/default/files/docs/Commission_2014_05_08.pdf','Indexed text describes DRI 423-M7 and a 2,090-square-foot science addition. Original PDF download denied (HTTP 403); not in cache.'),
 ('R-2026','West Tisbury planning agenda','2026-02-05','Exact tract / reference','https://www.westtisbury-ma.gov/AgendaCenter/ViewFile/ArchivedAgenda/_02052026-864','Search-index text referred to 317-square-foot conference and 734-square-foot office additions on map 16, lots 96 and 96.3. Original returned HTTP 404. This is a proposal reference, not proof of completed work.'),
 ('R-1994','1994 coastal aerial service','1994','Exact tract / gap','https://arcgisserver.digital.mass.gov/arcgisserver/rest/services/AGOL/ColorCoastalImagery1994/ImageServer','Queries in two coordinate systems returned blank NoData at the school tract. No 1994 image is included; this is not proof that no usable 1994 photograph exists elsewhere.')]
for id,title,date,scope,url,note in references:
    add(id,title,date,scope,[],url,note,'Source retains its stated rights; reference only.', 'Reference / not cached')

# Coordinates and reusable geographic plates.
def merc(lon,lat):
    return lon*20037508.342789244/180, math.log(math.tan((90+lat)*math.pi/360))*20037508.342789244/math.pi
def point(lon,lat,bb,size):
    x,y=merc(lon,lat)
    return ((x-bb[0])/(bb[2]-bb[0])*size[0],(bb[3]-y)/(bb[3]-bb[1])*size[1])
def font(n,bold=False): return ImageFont.truetype(BOLD if bold else FONT,n)
def wrapdraw(d,text,xy,width,ft,fill,spacing=5):
    words=text.split(); lines=[]; line=''
    for word in words:
        test=(line+' '+word).strip()
        if d.textlength(test,font=ft)>width and line: lines.append(line); line=word
        else: line=test
    if line: lines.append(line)
    x,y=xy
    for line in lines: d.text((x,y),line,font=ft,fill=fill); y+=ft.size+spacing
    return y
def marked_image(path,bb,labels=True):
    im=Image.open(path).convert('RGB'); d=ImageDraw.Draw(im)
    for f in parcels['features']:
        pts=[point(lon,lat,bb,im.size) for lon,lat in f['geometry']['coordinates'][0]]
        color=CYAN if f['properties']['MAP_PAR_ID']=='16-96' else GOLD
        d.line(pts,fill='#132b32',width=9,joint='curve'); d.line(pts,fill=color,width=4,joint='curve')
        if labels:
            x=sum(p[0] for p in pts[:-1])/(len(pts)-1); y=sum(p[1] for p in pts[:-1])/(len(pts)-1)
            label=f['properties']['MAP_PAR_ID']; ft=font(22,True)
            tb=d.textbbox((x,y),label,font=ft,anchor='mm')
            d.rectangle((tb[0]-9,tb[1]-6,tb[2]+9,tb[3]+6),fill=NAVY)
            d.text((x,y),label,font=ft,fill=color,anchor='mm')
    # North and scale are display aids, independent of parcel alignment.
    d.rectangle((im.width-90,16,im.width-16,123),fill=NAVY)
    d.text((im.width-53,27),'N',font=font(22,True),fill='white',anchor='mt')
    d.polygon([(im.width-53,57),(im.width-66,88),(im.width-53,81),(im.width-40,88)],fill='white')
    meters=100 if labels else 500
    pixels=meters/(math.cos(math.radians(41.4195))*(bb[2]-bb[0])/im.width)
    x=22; y=im.height-38
    d.rectangle((12,y-34,x+pixels+15,y+22),fill=NAVY)
    d.line((x,y,x+pixels,y),fill='white',width=5)
    d.line((x,y-6,x,y+6),fill='white',width=3);d.line((x+pixels,y-6,x+pixels,y+6),fill='white',width=3)
    d.text((x,y-29),f'{meters} m',font=font(20),fill='white')
    return im
def plate(im,title,subtitle,footer,out):
    w=1160; h=1270
    result=Image.new('RGB',(w,h),PAPER); d=ImageDraw.Draw(result)
    d.rectangle((0,0,w,142),fill=NAVY)
    d.text((44,26),title,font=font(38,True),fill='white')
    wrapdraw(d,subtitle,(44,84),w-88,font(20),fill='#d3e8e9')
    fitted=ImageOps.contain(im,(1072,970),Image.Resampling.LANCZOS)
    result.paste(fitted,((w-fitted.width)//2,160+(970-fitted.height)//2))
    wrapdraw(d,footer,(44,1150),w-88,font(18),fill=NAVY)
    result.save(out,quality=94)

for a in imagery:
    if not a.get('file'):continue
    year=a['date_label'];out=V/f'{year}_aerial_parcel_plate.jpg'
    im=marked_image(M/a['file'],bbox)
    im.save(V/f'{year}_aerial_overlay.jpg',quality=96)
    plate(im,year.replace('_','–')+' | MVPCS and its immediate surroundings',
        '420 & 424 State Road · West Tisbury · north up',
        'Cyan: lot 16-96. Gold: lot 16-96-3 (school). Current FY2026 assessor boundaries, not a survey or historical lot lines. '+masscredit+'.',out)
    for r in catalog:
        if r['id']=='A'+year:r['files'].extend([rel(out),rel(V/f'{year}_aerial_overlay.jpg')])
satim=marked_image(M/'Sentinel2_2024_regional_satellite.jpg',sat['bbox'],False)
plate(satim,'2024 | Satellite context','Sentinel-2 annual mosaic · tract outlined at center · north up',
    'Annual composite, not a single-date image. '+sat['credit']+'. CC BY-NC-SA 4.0. Boundaries: MassGIS FY2026, approximate.',V/'2024_satellite_parcel_plate.jpg')
catalog[[r['id'] for r in catalog].index('S01')]['files'].append(rel(V/'2024_satellite_parcel_plate.jpg'))

# Compact preview and chronological gallery; no color correction to underlying imagery.
gallery=Image.new('RGB',(1800,2050),PAPER);d=ImageDraw.Draw(gallery)
d.rectangle((0,0,1800,185),fill=NAVY)
d.text((54,40),'THE MVPCS TRACT',font=font(57,True),fill='white')
d.text((57,119),'Nine dated aerial views · 420 & 424 State Road, West Tisbury',font=font(28),fill='#c8e6e6')
dates=['1999','2003','2005','2008_2009','2013_2014','2019','2021','2023','2025']
for i,year in enumerate(dates):
    x=54+(i%3)*575;y=220+(i//3)*578
    img=Image.open(V/f'{year}_aerial_overlay.jpg').resize((542,542),Image.Resampling.LANCZOS)
    gallery.paste(img,(x,y));d.rectangle((x,y,x+168,y+49),fill=NAVY)
    d.text((x+13,y+8),year.replace('_','–'),font=font(26,True),fill='white')
wrapdraw(d,'Same extent in every frame. Cyan and gold outlines are current assessor parcels, not historical boundaries. Latest acquired imagery: 2025. Source: MassGIS / Commonwealth of Massachusetts EOTSS.',(54,1960),1690,font(23),NAVY)
preview=ROOT/'MVPCS_Aerial_Timeline.jpg';gallery.save(preview,quality=94)
shutil.copy2(preview,V/preview.name)

# Evidence summaries and gaps are separate from image metadata.
findings=[
 {'finding':'Two current parcels define this collection.','evidence':'FY2026 MassGIS: 420 State Road, lot 16-96, 154,202 sq ft; 424 State Road, lot 16-96-3, 162,043 sq ft. Both list Options in Education Inc.','source_ids':['P01'],'confidence':'Direct current assessor record.'},
 {'finding':'The current school dates to 1996.','evidence':'The school parcel has assessor year built 1996. A recorded deed dated 29 April 1996 is indexed to Options in Education Inc. Contemporary September 1996 coverage describes new construction. The school history gives an opening date of 16 September 1996.','source_ids':['P01','P02','N1996b','R-SCHOOL'],'confidence':'Strong agreement across independent dated records.'},
 {'finding':'The tract was mapped as woodland before the school.','evidence':'The 1972 USGS quadrangle has green woodland tint across the current parcel overlay. Its revision used 1969 aerial photographs and was field checked in 1972.','source_ids':['T1972'],'confidence':'Map-based interpretation; not a parcel survey or proof of every earlier use.'},
 {'finding':'No earlier building at the exact school footprint has been identified in this cache.','evidence':'The acquired pre-school maps are too generalized to prove the absence of small buildings. The 1951 map does not encode woodland in the same way as the 1972 sheet. A pre-1996 aerial and the complete title chain remain important missing evidence.','source_ids':['T1951','T1972','R-1994','P02'],'confidence':'Open question, not a finding of permanent vacancy.'},
 {'finding':'The wider historical record reaches much farther back than the parcel evidence.','evidence':'An acquired 1698 map and nineteenth-century community papers document the wider Island and Christiantown setting. Tribal history describes Wampanoag presence on Noepe for at least 10,000 years. No archaeological or title connection to this exact tract was established.','source_ids':['H1698','Dc821mx42g','D0p09bk77g','D7366dr72r','R-TRIBE'],'confidence':'Regional context only.'}
]
(C/'findings.json').write_text(json.dumps(findings,indent=2,ensure_ascii=False))
gaps=[
 {'priority':1,'record':'Full 1996 deed, Book 675/page 665 (2 pages)','why':'Its legal description and prior-deed citation are the best next step to a proven chain of title.','status':'Registry index and metadata acquired; document-image viewer failed.','where':registryurl},
 {'priority':2,'record':'Plans referenced by that deed and recorded decisions','why':'Needed to distinguish historical subdivision boundaries, access, easements and any former structures. Assessor polygons are not substitutes.','status':'No legal survey acquired. Indexed decisions: 673/11 (1996-03-22), 674/871 (1996-04-19), 704/237 (1997-07-14), 736/598 (1998-07-23), 1356/396 (2014-08-29). Easement 682/724 (1996-08-05).','where':registryurl},
 {'priority':3,'record':'Possible predecessor trust records: 560/499, 560/488 and 617/179','why':'Could lead from Middletown Village Trust toward earlier owners.','status':'Name-index leads only. 560/499 deed and 560/488 declaration dated 1991-06-26; 617/179 deed dated 1993-10-22. NOT established as conveyances of these same lots until the instruments are read.','where':registryurl},
 {'priority':4,'record':'Pre-school aerial photographs and local assessor cards','why':'Needed to see the ground immediately before construction and distinguish woods, fields, tracks or buildings.','status':'No pre-1996 aerial acquired. The 1994 public service returned NoData here. Earliest usable acquired aerial is 1999. Museum catalog lists a 1985 assessor map (2012.035.017), image not acquired.','where':'https://mvmuseum.org/wp-content/uploads/2019/06/Maps_Collection_Index.pdf'},
 {'priority':5,'record':'Earlier deeds, probate files and wills tied to verified owners','why':'Needed before claiming a particular farm, house, estate or named family occupied the school tract.','status':'No parcel-specific will acquired. The 1828 estate inventory is contextual and has not been tied to this land.','where':'https://mvmuseum.org/EAD_FindingAids/findingaid_get.php?record-unit=RU505'},
 {'priority':6,'record':'Higher-resolution historic local plans and Christiantown boundary material','why':'Could establish whether older labeled uses and land divisions overlap the modern campus.','status':'Museum map identifiers are retained as retrieval leads in R-MVM. No historical boundary has been asserted or overlaid without verification.','where':'https://mvmuseum.org/wp-content/uploads/2019/06/Maps_Collection_Index.pdf'}
]
(C/'research_gaps.json').write_text(json.dumps(gaps,indent=2,ensure_ascii=False))
(C/'source_catalog.json').write_text(json.dumps(catalog,indent=2,ensure_ascii=False))
with (C/'source_catalog.csv').open('w',newline='',encoding='utf-8-sig') as f:
    writer=csv.DictWriter(f,fieldnames=list(catalog[0]));writer.writeheader()
    for r in catalog:writer.writerow({**r,'files':' | '.join(r['files'])})

readme='''# MVPCS land evidence collection

Research snapshot: 23 September 2026. Site: Martha’s Vineyard Public Charter School,
420 and 424 State Road, West Tisbury, Massachusetts. Current parcels 16-96 and
16-96-3. This is a finite collection of material acquired online, not an exhaustive
search of every offline record or a completed title examination.

## Start here

Open `index.html` in a browser after extracting the entire ZIP. It works offline;
original source links require an internet connection. Open `MVPCS_Land_Evidence_Guide.pdf`
for the illustrated narrative. Use `05_Research_Catalog/source_catalog.csv` or JSON
for source URLs, dates, evidence scope, acquisition status and rights.

## What the evidence supports

The current school building dates to 1996. The registry indexes the acquisition
deed to Options in Education Inc. on 29 April 1996, Book 675/page 665, for $240,000.
That same deed is cited on both current assessor lots; the sale price is not two
separate purchases. Their reported areas total about 7.26 acres.

The 1972 USGS map depicts woodland across the current tract. It was revised from
1969 aerial photographs and field checked in 1972. This is the clearest acquired
pre-school land-cover evidence. The 1951 sheet locates the site in an earlier road
landscape, but white map background is not evidence of cleared land. No named
earlier building, farm or owner has been established for the exact school footprint.

The oldest acquired historical map is dated 1698. The 1811, 1828 and 1861 papers,
the Christiantown chapel photo, and the 2011 oblique aerial provide surrounding-area
context. They are NOT established parts of the school parcel’s title or occupancy
history. The 1828 item is an estate inventory, not a will.

## Contents and use

01_Maps_and_Imagery: nine unmarked aerial mosaics, world files, current parcel
GeoJSON, a 2024 satellite composite, two original USGS PDFs and unmarked map crops.
02_Public_Records: actual 1996 deed-index screenshot and rendered text.
03_Newspaper_References: short Gazette headline screenshot; article URLs and
paraphrases are in the catalog rather than copyrighted full-article copies.
04_Historical_Context: full native scans where available, lower-resolution Harvard
Forest map reproductions, historic community documents and nearby photographs.
05_Research_Catalog: provenance, source metadata, findings, gaps and SHA-256 hashes.
06_Visual_Plates: annotated maps and a nine-frame aerial timeline.

## Dating and image transformations

The service called “1990s” was photographed over the Vineyard in 1999, as shown by
the supplied MassGIS flight-status PDF. The service called “2001” uses April 2003
photography for the islands. Other labels follow dataset years/ranges; exact local
flight days were not verified. The latest acquired aerial is 2025, not a live 2026
view. The satellite view is an annual 2024 mosaic, not one day’s exposure.

Aerials are north-up Web Mercator tile mosaics (EPSG:3857), with no missing tiles
in the saved extent. JPG world files (.jgw) use that CRS; set EPSG:3857 explicitly
when loading them into GIS. GeoJSON is longitude/latitude (EPSG:4326). Current
assessor outlines on earlier images do not show historical lot boundaries.
Scales use the approximate ground correction at latitude 41.4195 degrees.

USGS close-ups were rendered from the original PDFs. Modern parcel outlines were
transformed into the PDFs’ NAD27 polyconic map coordinates using their embedded
georeferencing. Registration and historic map accuracy are limited; overlays are
approximate and are not legal surveys. The full original PDFs remain unaltered.

Digital Commonwealth scans were acquired at full native IIIF resolution. The 1698
map reproduction was cropped only to remove a modern caption below the map. Its
photographic glare remains. Other historical originals were not retouched. The
2011 Foster photo is supplied unaltered, under its stated no-derivatives license.

## Gaps and unresolved evidence

The complete 1996 deed image, a legal survey, parcel-specific probate/will records,
and a pre-1996 aerial were not obtained. A 1994 imagery service returned NoData.
Several Commission PDFs returned HTTP 403 and a 2026 agenda returned HTTP 404.
Reference-only entries are clearly marked. No blank image is passed off as aerial
evidence and no candidate predecessor deed is presented as a proven link.

The highest-value next retrieval is the two-page deed at 675/665, followed by its
prior-deed and plan references. See `research_gaps.json` for precise identifiers.

## Rights and attribution

Each source retains its own rights; this ZIP has no blanket open license. MassGIS:
MassGIS (Bureau of Geographic Information), Commonwealth of Massachusetts EOTSS.
USGS government maps are public domain. Historic archival items carry repository
rights statements in the included metadata. The 2011 oblique photo is © David R.
Foster, Harvard University, CC BY-NC-ND 4.0. The chapel photo’s rights were not
evaluated by its repository. Newspaper content belongs to the Vineyard Gazette.

Satellite: Sentinel-2 cloudless - https://s2maps.eu by EOX IT Services GmbH
(Contains modified Copernicus Sentinel data 2024), CC BY-NC-SA 4.0.
https://creativecommons.org/licenses/by-nc-sa/4.0/
Derived satellite plate retains that license. Source attribution is also in the
catalog and on visual plates. This research collection does not grant additional
commercial reuse or republication rights to third-party material.
'''
(B/'README.md').write_text(readme)

# Offline gallery: no remote scripts, no web dependencies, original files remain accessible.
cards=[]
for r in catalog:
    img=next((p for p in r['files'] if p.endswith(('.jpg','.png')) and 'plate' in p),None)
    if not img:img=next((p for p in r['files'] if p.endswith(('.jpg','.png'))),None)
    # For no-derivatives photo, show complete image using object-fit:contain, never crop.
    pic=f'<a href="{html.escape(img)}"><img loading="lazy" src="{html.escape(img)}" alt="{html.escape(r["title"])}"></a>' if img else '<div class="noimg">Source reference</div>'
    files=''.join(f'<li><a href="{html.escape(p)}">{html.escape(Path(p).name)}</a></li>' for p in r['files'])
    cards.append(f'''<article data-search="{html.escape(' '.join(str(r[k]) for k in ['id','title','date','scope','notes','status']).lower())}">
    {pic}<div class="cardbody"><small>{html.escape(r['id'])} · {html.escape(r['scope'])}</small><h3>{html.escape(r['title'])}</h3><p class="date">{html.escape(r['date'])} · {html.escape(r['status'])}</p><p>{html.escape(r['notes'])}</p><a href="{html.escape(r['url'])}" target="_blank" rel="noopener">Original source ↗</a><details><summary>Files &amp; rights ({len(r['files'])} files)</summary><ul>{files}</ul><p>{html.escape(r['rights'])}</p></details></div></article>''')
index='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MVPCS land evidence collection</title>
<style>:root{--navy:#102f3b;--paper:#f6f4ef;--teal:#007e88}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--navy);font:16px/1.55 system-ui,sans-serif}header{padding:48px max(5vw,24px);background:var(--navy);color:white}h1{font-size:clamp(32px,5vw,62px);line-height:1.1;max-width:900px;margin:12px 0}header p{max-width:850px;color:#d5e9e9}main{max-width:1380px;margin:auto;padding:32px}a{color:var(--teal);text-underline-offset:3px}header a{color:#82e9e9}.intro{display:grid;grid-template-columns:1.2fr 1fr;gap:30px;margin:20px 0 35px}.box{padding:24px;background:white;border:1px solid #d7dfde;border-radius:10px}.compare{position:relative;max-width:650px;aspect-ratio:1;overflow:hidden}.compare img{position:absolute;width:100%;height:100%;object-fit:contain;top:0;left:0}.compare .late{clip-path:inset(0 0 0 50%)}.compare .split{position:absolute;left:50%;top:0;bottom:0;width:3px;background:white;pointer-events:none}.compare-label{position:absolute;top:12px;padding:5px 10px;background:var(--navy);color:white;font-weight:bold}.left{left:12px}.right{right:12px}input[type=range]{width:100%}label{font-weight:650}.filters{position:sticky;top:0;background:var(--paper);padding:16px 0;z-index:5;display:flex;gap:12px;flex-wrap:wrap}input[type=search],select{padding:13px;border:1px solid #8babab;border-radius:5px;font:inherit}input[type=search]{flex:1;min-width:210px}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:22px}article{background:white;border:1px solid #d5dfde;border-radius:8px;overflow:hidden}article img{width:100%;height:265px;object-fit:contain;background:#e8e9e3}article h3{font-size:21px;line-height:1.25;margin:8px 0}.cardbody{padding:20px}small,.date{font-size:13px;color:#425f69}.date{font-weight:700}.noimg{height:110px;background:#e5ecea;display:grid;place-items:center;font-size:22px;font-weight:bold}details{margin-top:16px;font-size:14px}details ul{padding-left:18px;overflow-wrap:anywhere}.empty{display:none}.foot{margin:40px 0;color:#46616a;font-size:14px}@media(max-width:950px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.intro{grid-template-columns:1fr}}@media(max-width:600px){main{padding:20px}.grid{grid-template-columns:1fr}}[hidden]{display:none!important}</style>
<header><div>WEST TISBURY · MARTHA’S VINEYARD</div><h1>The land beneath MVPCS</h1><p>A dated evidence collection for 420 and 424 State Road: aerial photographs, satellite imagery, historical maps, registry evidence, newspaper references and archival scans. Compiled 23 September 2026.</p><a href="MVPCS_Land_Evidence_Guide.pdf">Read the illustrated guide</a> · <a href="05_Research_Catalog/source_catalog.csv">Download source catalog</a> · <a href="README.md">Read methods and limitations</a></header>
<main><section class="intro"><div class="box"><h2>What is established?</h2><p><strong>The school dates to 1996, and a 1972 USGS map depicts woodland across the tract.</strong> The two current assessor parcels total about 7.26 acres. No earlier named building or farm has yet been demonstrated at the exact school footprint.</p><p>The oldest acquired map is dated 1698. Earlier community history and nineteenth-century archival records provide context; they are not established links in the school’s chain of title.</p><p><strong>Key missing evidence:</strong> the full 1996 deed instrument, its cited plans and earlier deeds, a pre-1996 aerial, and any probate records tied to verified former owners. The collection includes an actual deed-index screenshot, not the full deed.</p><p><a href="05_Research_Catalog/research_gaps.json">Precise next-retrieval targets</a></p></div><div class="box"><h2>Compare the same ground</h2><div class="compare"><img src="06_Visual_Plates/1999_aerial_overlay.jpg" alt="1999 aerial with current parcels"><img class="late" id="late" src="06_Visual_Plates/2025_aerial_overlay.jpg" alt="2025 aerial with current parcels"><div class="split" id="split"></div><div class="compare-label left">1999</div><div class="compare-label right">2025</div></div><label for="slider">Move the divider</label><input id="slider" type="range" min="0" max="100" value="50"><p class="date">Cyan and gold: current FY2026 assessor parcels. Source: MassGIS. Latest acquired imagery is 2025; not a live 2026 view.</p></div></section>
<h2>Browse the evidence</h2><div class="filters"><input id="search" type="search" placeholder="Search dates, parcels, deeds, Christiantown…" aria-label="Search collection"><select id="scope" aria-label="Filter evidence scope"><option value="">All evidence</option><option value="exact tract">Exact tract</option><option value="regional">Regional context</option><option value="nearby">Nearby context</option><option value="unverified">Unverified leads</option><option value="not cached">References not cached</option></select><span id="count"></span></div><section class="grid">'''+''.join(cards)+'''</section><p class="empty" id="empty">No entries match this search.</p><div class="foot">This offline catalog distinguishes acquired files from references. Each item retains its own rights and attribution; there is no blanket license for the collection. Historical boundaries have not been inferred from modern parcel outlines. See the README and source catalog for methods, acquisition gaps and reuse terms.</div></main>
<script>const search=document.getElementById('search'),scope=document.getElementById('scope'),cards=[...document.querySelectorAll('article')];function filter(){const terms=search.value.toLowerCase().split(/\\s+/).filter(Boolean),s=scope.value;let count=0;for(const card of cards){const t=card.dataset.search;card.hidden=!(terms.every(q=>t.includes(q))&&(!s||t.includes(s)));if(!card.hidden)count++}document.getElementById('count').textContent=count+' sources';document.getElementById('empty').style.display=count?'none':'block'}search.addEventListener('input',filter);scope.addEventListener('change',filter);filter();document.getElementById('slider').addEventListener('input',e=>{document.getElementById('late').style.clipPath='inset(0 0 0 '+e.target.value+'%)';document.getElementById('split').style.left=e.target.value+'%'})</script></html>'''
(B/'index.html').write_text(index)

# Illustrated PDF guide.
OUT=ROOT/'MVPCS_Land_Evidence_Guide.pdf'
W,HIGH=792,612
cv=canvas.Canvas(str(OUT),pagesize=(W,HIGH),pageCompression=1)
cv.setTitle('The land beneath MVPCS — evidence guide')
cv.setAuthor('Research collection compiled for the user, 23 September 2026')
styles={
 'body':ParagraphStyle('body',fontName='DV',fontSize=10.2,leading=15,textColor=HexColor(NAVY),spaceAfter=7),
 'small':ParagraphStyle('small',fontName='DV',fontSize=8.2,leading=11.5,textColor=HexColor('#46616a')),
 'side':ParagraphStyle('side',fontName='DV',fontSize=10.0,leading=14.4,textColor=HexColor(NAVY)),
 'lead':ParagraphStyle('lead',fontName='DVB',fontSize=17,leading=23,textColor=HexColor(NAVY)),
 'white':ParagraphStyle('white',fontName='DV',fontSize=12,leading=18,textColor=HexColor('#d4e8e9'))}
pagecount=0
def para(txt,x,y,w,style='body'):
    p=Paragraph(txt,styles[style]);_,ht=p.wrap(w,1000);p.drawOn(cv,x,y-ht);return y-ht
def page(title,kicker='MVPCS LAND EVIDENCE',sub=None):
    global pagecount
    pagecount+=1;cv.setFillColor(HexColor(PAPER));cv.rect(0,0,W,HIGH,fill=1,stroke=0)
    cv.bookmarkPage('p'+str(pagecount));cv.addOutlineEntry(title,'p'+str(pagecount),level=0)
    cv.setFillColor(HexColor(TEAL));cv.setFont('DVB',8.5);cv.drawString(36,577,kicker)
    cv.setFillColor(HexColor(NAVY));cv.setFont('DVB',23);cv.drawString(36,545,title)
    if sub:para(sub,36,528,720,'small')
    cv.setStrokeColor(HexColor('#c9d6d5'));cv.line(36,38,756,38)
    cv.setFont('DV',7.5);cv.setFillColor(HexColor('#47636b'));cv.drawString(36,23,'420 & 424 State Road · West Tisbury | Research snapshot: '+DATE)
    cv.drawRightString(756,23,str(pagecount))
def end():cv.showPage()
def imagefit(path,x,y,w,h):
    im=Image.open(path).convert('RGB')
    im.thumbnail((2200,2200),Image.Resampling.LANCZOS)
    iw,ih=im.size;scale=min(w/iw,h/ih);ww=iw*scale;hh=ih*scale
    encoded=io.BytesIO();im.save(encoded,format='JPEG',quality=89,optimize=True);encoded.seek(0)
    cv.drawImage(ImageReader(encoded),x+(w-ww)/2,y+(h-hh)/2,width=ww,height=hh)
def source_link(id,x,y,w=190):
    r=next(r for r in catalog if r['id']==id)
    safe=html.escape(r['url'],quote=True)
    return para(f'<b>{html.escape(id)}</b> · <a href="{safe}" color="#007e88">Open original source</a>',x,y,w,'small')
def visual(title,img,id,caption,detail='',scope='EXACT TRACT / VICINITY'):
    page(title,scope)
    imagefit(img,36,60,500,459)
    y=para(caption,558,506,198,'lead')
    y=para(detail,558,y-18,198,'side')
    source_link(id,558,y-22,198)
    end()
def blocks(title,items,kicker='FINDINGS & EVIDENCE'):
    page(title,kicker)
    y=510
    for head,txt in items:
        y=para('<b>'+head+'</b>',40,y,708,'body')
        y=para(txt,40,y-4,708,'body')-15
    if y<48:raise RuntimeError(f'Overflow on {title}: {y}')
    end()

# Cover
pagecount+=1;cv.setFillColor(HexColor(NAVY));cv.rect(0,0,W,HIGH,fill=1,stroke=0)
imagefit(V/'2025_aerial_overlay.jpg',340,0,452,612)
cv.setFillColor(HexColor(NAVY));cv.rect(0,0,360,612,fill=1,stroke=0)
cv.setFillColor(HexColor('#6be2e6'));cv.setFont('DVB',10);cv.drawString(36,563,'WEST TISBURY / MARTHA’S VINEYARD')
for i,line in enumerate(['The land','beneath','MVPCS']):
    cv.setFillColor(HexColor('#ffffff'));cv.setFont('DVB',45);cv.drawString(34,481-i*55,line)
para('Maps, aerial photographs, satellite imagery, registry evidence and archival documents for 420 and 424 State Road.',36,280,284,'white')
para('A research guide and source cache<br/>Compiled '+DATE,36,158,284,'white')
para('Cover: 2025 MassGIS aerial. Cyan and gold show current assessor parcels. These are not legal survey boundaries.',36,85,284,'white')
end()
blocks('What the evidence establishes',[
 ('The school dates to 1996.','The assessor records 1996 as the school building’s year of construction. The registry indexes a 29 April 1996 acquisition by Options in Education Inc. Contemporary newspaper coverage describes new construction that September. [P01, P02, N1996b, R-SCHOOL]'),
 ('Before the school, the tract was mapped as woodland.','The 1972 USGS quadrangle places green woodland tint across the current parcel outlines. It was revised from 1969 photography and field checked in 1972. This is the strongest acquired pre-school land-cover evidence. [T1972]'),
 ('An earlier building or named farm remains unproven.','No acquired document identifies a predecessor building at the exact school footprint. That does not establish that the land was never cleared, farmed or occupied. A complete title chain and a pre-1996 aerial are still missing.'),
 ('The older material has a wider geographic scope.','The acquired maps reach back to 1698. Christiantown papers and photographs illuminate the neighboring community; none has been demonstrated to describe these exact lots. Island-wide Wampanoag history reaches much further back. [H1698, R-TRIBE]')])
blocks('How to read this collection',[
 ('Exact tract','Current parcels, nine aerials, the deed index, school reports and the USGS location overlays address the campus or its immediate surroundings. Their precision and dates still differ.'),
 ('Nearby and regional context','Historic Island maps, the Christiantown papers, chapel photograph and 2011 oblique aerial are labeled as context. Their presence here does not establish that a depicted person, building or land use belonged to the school tract.'),
 ('Acquired file versus reference','The ZIP contains original downloaded files where obtainable, plus unmarked map crops and derived visual plates. A reference-only entry provides a source link or retrieval lead; it does not mean that the full source was acquired.'),
 ('Offline access','Extract the ZIP and open index.html for search, image previews, source links and a 1999/2025 comparison slider. The CSV and JSON catalogs carry source IDs used in this guide. Full-resolution scans are retained even when this PDF shows only one page.')])
page('The two current parcels','CURRENT RECORD · FY2026')
imagefit(V/'2025_aerial_overlay.jpg',36,73,432,432)
y=para('About 7.26 acres in two assessor lots',490,506,260,'lead')
y=para('<b>16-96 · 420 State Road</b><br/>154,202 sq ft · about 3.54 acres<br/>No building area recorded in this assessor entry.<br/><br/><b>16-96-3 · 424 State Road</b><br/>162,043 sq ft · about 3.72 acres<br/>School; year built 1996; recorded building area 16,726 sq ft.<br/><br/><b>Owner on both:</b> Options in Education Inc.<br/><b>Deed on both:</b> 675/665, 29 April 1996. The shared $240,000 price is one deed consideration, not two separate sales.',490,y-18,260,'body')
source_link('P01',490,y-16,260)
end()
blocks('A chronology with different levels of certainty',[
 ('2026 records / 2025 photograph','FY2026 assessor data establishes the current lot identifiers. The newest acquired aerial was photographed in 2025; the collection has no live 2026 overhead image.'),
 ('1996–2025: the school period','1996 acquisition and new construction are directly documented. Nine aerials track the developed campus from 1999 through 2025. Newspaper reports describe later additions in 1997 and 2009.'),
 ('1972 and 1951: before the school','The 1972 map depicts woodland at the tract. The 1951 edition supplies earlier road and topographic context but does not use the same forest shading.'),
 ('1698–1913: broader documentary context','Island and town maps, nineteenth-century Christiantown records and a historic chapel photograph document the surrounding landscape and community. Exact tract ownership has not been traced through them.'),
 ('Before colonial maps','The Wampanoag Tribe’s history describes at least 10,000 years of presence on Noepe. No archaeological record specifically from the school parcel was acquired. Earlier European map dates do not mark the beginning of the land’s human history.')])

for a in imagery:
    if not a.get('file'):continue
    year=a['date_label']; label=year.replace('_','–')
    detail='Cyan: 16-96, the northern lot.<br/><br/>Gold: 16-96-3, containing the school.<br/><br/>All nine aerials use the same extent and current FY2026 assessor outlines. The unmarked originals and world files are included.'
    if year=='2025':detail+=' <br/><br/>Latest acquired overhead image; not a live view of September 2026.'
    if year=='2003':detail+='<br/><br/>Although the service is named “2001,” MassGIS dates the island photography to April 2003.'
    if year=='1999':detail+='<br/><br/>Year established by the MassGIS flight-status map. It already postdates the school’s opening.'
    if '_' in year:detail+='<br/><br/>Date is the published dataset range; the local flight day was not established.'
    visual(label+' · aerial photograph',V/f'{year}_aerial_overlay.jpg','A'+year,'The same tract, through time',detail,'EXACT TRACT · MASSGIS')
page('1999 and 2025 · compare the same ground','EXACT TRACT · MASSGIS')
for x,year in [(36,'1999'),(414,'2025')]:
    cv.setFillColor(HexColor(NAVY));cv.setFont('DVB',16);cv.drawString(x,507,year)
    imagefit(V/f'{year}_aerial_overlay.jpg',x,133,342,342)
para('Both photographs postdate the school’s establishment. Buildings, circulation and clearing can be compared directly, while current parcel outlines provide a consistent reference. Image season, resolution and radiometry vary. The offline catalog supplies a movable comparison divider.',36,104,720,'body')
end()
visual('2024 · satellite context',V/'2024_satellite_parcel_plate.jpg','S01','The wider setting',
    'Sentinel-2 annual cloudless mosaic, about 3 km across on the ground.<br/><br/>The two school lots are outlined at the center. Source pixels are approximately 10 m, so this image is better for landscape context than individual school structures.<br/><br/>EOX IT Services GmbH; modified Copernicus Sentinel data 2024. CC BY-NC-SA 4.0.','VICINITY · SATELLITE COMPOSITE')
visual('1972 · woodland at the future campus',V/'USGS_1972_school_vicinity_overlay.jpg','T1972','Pre-school land cover',
    'The green woodland tint crosses the current school parcels, outlined in magenta.<br/><br/>Revision used 1969 aerial photographs; field checked in 1972. Original scale 1:25,000.<br/><br/>This is map evidence of woodland, not a proof that no earlier small structure or clearing ever existed. Modern overlay is approximate.','EXACT TRACT / VICINITY · USGS')
visual('1951 · an earlier map of the vicinity',V/'USGS_1951_school_vicinity_overlay.jpg','T1951','Roads and terrain before the school',
    'Surveyed 1942 and revised 1951; cataloged print year 1952. Original scale 1:31,680.<br/><br/>This edition does not use the green forest tint of the 1972 map. Its white background is not evidence that this land was cleared.<br/><br/>Magenta outlines show current parcels, registered approximately to the historic sheet.','EXACT TRACT / VICINITY · USGS')
visual('29 April 1996 · the acquisition record',B/'02_Public_Records/MVPCS_1996_deed_index.jpg','P02','An actual registry index screenshot',
    'Book 675 / page 665<br/>Document 2683 · two pages<br/>Consideration: $240,000<br/><br/>Grantors indexed: Mary E. Cournoyer, trustee, and Middletown Village Trust.<br/><br/>Grantee: Options in Education Inc.<br/><br/>The full deed instrument was not acquired. Its legal description and prior-deed references remain the key next evidence.','EXACT TRACT · REGISTRY EVIDENCE')
page('1995–2009 · contemporary school reporting','EXACT TRACT · NEWSPAPER REFERENCES')
imagefit(B/'03_Newspaper_References/MVPCS_Gazette_1996_09_06_headline.jpg',40,408,710,105)
y=390
for id,title,date,url,note in news:
    y=para('<b>'+date+'</b> — '+html.escape(note),40,y,710,'body')
    y=source_link(id,40,y-2,710)-13
if y<46:raise RuntimeError('News page overflow '+str(y))
end()
visual('1913 · the Island’s road geography',H/'1913_Eldridge_Vineyard_Map_p01.jpg','D79408315w','An Island-wide reference',
    'Eldridge’s map of Martha’s Vineyard, preserved by the Boston Public Library.<br/><br/>Useful for reading the established road network and named places. It is not a cadastral survey of the school lots.<br/><br/>Full native image is in the collection; no modern parcel boundary has been placed on this map.','REGIONAL CONTEXT · HISTORIC MAP')
visual('1831 · Tisbury before the town division',H/'1831_Dunham_Plan_of_Tisbury_p01.jpg','D25152j880','A town-scale plan',
    'Thomas Dunham’s plan, dated April 1831, Massachusetts Archives.<br/><br/>West Tisbury separated from Tisbury in 1892, so earlier records may use the older town name.<br/><br/>The map has not been georeferenced closely enough here to identify an owner or a structure at the exact school footprint.','REGIONAL CONTEXT · HISTORIC PLAN')
visual('Circa 1850 · Whiting’s landscape',H/'Whiting_1850_map.jpg','H1850','A broader land-use picture',
    'Harvard Forest’s reproduction associated with Henry Laurens Whiting’s mid-nineteenth-century surveys.<br/><br/>The source discusses surveys from 1844–1852 and a later chart. Treat the displayed date as approximate.<br/><br/>This reproduction is not used to assign a specific field, farm or owner to the school tract.','REGIONAL CONTEXT · MAP REPRODUCTION')
visual('1858 · Walling’s county map',H/'1858_Walling_County_Map.jpg','H1858','Regional geography',
    'A Harvard Forest reproduction of the map of Barnstable, Dukes and Nantucket counties.<br/><br/>The acquired copy is too small to establish a school-site building or ownership label reliably.<br/><br/>It is retained as a locator and a lead toward a higher-resolution original.','REGIONAL CONTEXT · MAP REPRODUCTION')
visual('1781 · the western Vineyard',H/'1781_DesBarres_Western_Vineyard.jpg','H1781','Coasts and landforms',
    'Des Barres chart of Buzzards Bay and western Martha’s Vineyard, reproduced by Harvard Forest.<br/><br/>This is regional coastal evidence, not a tract survey. No historical building or land use is inferred for MVPCS from this small reproduction.','REGIONAL CONTEXT · HISTORIC CHART')
visual('1776 · the eastern Vineyard and Nantucket',H/'1776_Nantucket_Eastern_Vineyard_Chart_p01.jpg','D7h149z539','A neighboring coastal chart',
    'A Des Barres chart from the Atlantic Neptune, preserved by the Boston Public Library.<br/><br/>The chart’s scope is eastern Martha’s Vineyard and Nantucket. It is included as neighboring coastal context, not as an exact view of the school tract.<br/><br/>Full-resolution source scan supplied.','REGIONAL CONTEXT · NOT A TRACT MAP')
visual('1698 · the earliest acquired historical map',H/'1698_Simon_Athearn_Vineyard_Map.jpg','H1698','An early Island-wide view',
    'Simon Athearn’s 1698 map, in a photographic reproduction hosted by Harvard Forest.<br/><br/>This is the oldest dated map acquired for the cache. It does not identify the modern school parcels.<br/><br/>The original reproduction has glare and limited resolution. Only a modern caption below the map was cropped away.','REGIONAL CONTEXT · HISTORIC MAP')
visual('1811 · a community letter',H/'1811_Wampanoag_Letter_to_Governor_p01.jpg','Dc821mx42g','Christiantown and Chappaquiddick voices',
    'Letter to Governor Elbridge Gerry, dated 28 October 1811. Massachusetts Archives.<br/><br/>All four source scans are included. This page is a preview; there is no claimed full transcription.<br/><br/>The document concerns neighboring communities. It has not been connected to ownership or use of the school tract.','NEARBY / REGIONAL CONTEXT · ARCHIVAL DOCUMENT')
visual('1828 · property in Christiantown',H/'1828_Christiantown_Chappaquiddick_Estate_Inventory_p02.jpg','D0p09bk77g','Houses, fields, woodland and livestock',
    'Community property inventory, 15–16 December 1828. Massachusetts Archives. The Christiantown schedule is shown; all six scans are included.<br/><br/>It lists household dwellings, improved land, detached woodland and animals.<br/><br/>“Estate” means property here. This is not a will or an established probate inventory. No link to the school tract has been proved.','NEARBY / REGIONAL CONTEXT · NOT A SCHOOL DEED')
visual('1861 · a report on Christiantown',H/'1861_Christiantown_Report_p01.jpg','D7366dr72r','The surrounding community in official records',
    'Massachusetts Archives report, 1861. All sixteen scans are supplied.<br/><br/>Government accounts reflect the officials who created them; the 1811 letter provides a different source perspective.<br/><br/>This report has not been demonstrated to describe the exact MVPCS lots.','NEARBY CONTEXT · ARCHIVAL DOCUMENT')
visual('Circa 1890–1940 · Mayhew Chapel',H/'circa1890_1940_Christiantown_Chapel_p01.jpg','Dz890s049v','A nearby building, not a predecessor school-site structure',
    'Mayhew Chapel, Christiantown. Photograph by Edward Lee Luce; Martha’s Vineyard Museum.<br/><br/>Date range follows the repository catalog.<br/><br/>No evidence places this building on the school parcels. Repository rights status: not evaluated; contact the museum for reuse information.','NEARBY CONTEXT · HISTORIC PHOTOGRAPH')
visual('7 October 2011 · North Tisbury from the air',H/'2011_North_Tisbury_Seven_Gates_Aerial_p01.jpg','Dpc28bt615','A wider oblique view',
    'North Tisbury to Seven Gates Farm. Photograph © David R. Foster; Harvard University.<br/><br/>Reproduced in full, without cropping or annotations. CC BY-NC-ND 4.0.<br/><br/>The exact school footprint has not been identified in this frame. It is a record of the surrounding landscape.','REGIONAL CONTEXT · OBLIQUE AERIAL')
blocks('The earlier history needs a geographic bridge',[
 ('Wampanoag land and continuing history','The Wampanoag Tribe of Gay Head (Aquinnah) describes at least 10,000 years of presence on Noepe. This is a living community history, not merely a preface to colonial settlement. No archaeological evidence specifically from the school parcel was acquired. [R-TRIBE]'),
 ('Christiantown nearby','Land Bank history and archival records provide a seventeenth- through nineteenth-century setting for the nearby community. Their geographic relationship to the current campus needs careful reconstruction from actual boundary and title records. [R-CHRIST, Dc821mx42g, D7366dr72r]'),
 ('Tisbury, then West Tisbury','The town’s history dates Tisbury to 1671 and West Tisbury’s separation to 1892. Earlier deeds, town records and plans should therefore also be sought under Tisbury. [R-TOWN]'),
 ('What has not been established','This collection does not identify a particular Indigenous settlement, colonial farm, house, estate or historic owner on the exact school footprint. Those questions remain open pending a proven chain of title and more precise early mapping.')])
blocks('The next records, in priority order',[
 ('1 · Read the two-page deed at 675/665','Acquire the instrument, copy its full legal description, then follow the previous deed and plan citations. The 1996 index identifies the acquisition but does not supply the boundaries in words.'),
 ('2 · Retrieve the associated plans and decisions','Registry leads: decisions 673/11 and 674/871 (1996); easement 682/724 (1996); later decisions 704/237 (1997), 736/598 (1998), 1356/396 (2014). A survey may appear among the cited plans or project files.'),
 ('3 · Test the predecessor trust leads','Middletown Village Trust index leads include 560/499 and declaration 560/488 (26 June 1991), and deed 617/179 (22 October 1993). They are candidates only; their connection to the same land must be proved from the instruments.'),
 ('4 · Fill the last pre-school image gap','A pre-1996 aerial and local assessor cards would best show the ground before construction. The museum catalog lists a 1985 assessor map, identifier 2012.035.017. The attempted 1994 public imagery service returned NoData here.'),
 ('5 · Follow verified owners into probate','Only after establishing the preceding owners should wills, inventories and estate divisions be treated as evidence about this tract. The acquired 1828 inventory has no demonstrated link.')])
blocks('Dating, methods and limits',[
 ('Correct the service names before reading the images','The “1990s” aerial is 1999 over the Vineyard, established by the included flight-status map. The “2001” service uses April 2003 photography on the islands. Mixed-year services retain their date ranges.'),
 ('Keep originals alongside overlays','Nine aerials share one extent. JPG world files use EPSG:3857; parcel GeoJSON uses EPSG:4326. Overlays show FY2026 assessor boundaries. USGS close-ups use embedded PDF georeferencing, with approximate alignment and map-scale limits.'),
 ('Distinguish unavailable from nonexistent','No usable 1994 tile, full deed instrument, legal survey or parcel-specific will was acquired. Some government PDFs were blocked and a 2026 agenda URL was missing. Those failures do not establish that the records do not exist.'),
 ('Resolve the date disagreement explicitly','Options in Education’s retrospective history refers to land/construction activity in 1995. The dated registry entry, assessor construction year and contemporary opening coverage support 1996. Both sources are retained in the catalog rather than silently reconciled.'),
 ('A finite online research collection','This cache contains the material obtained in this research session and precise leads for unfinished work. It is not an exhaustive archive search, a survey, or a completed examination of title.')])
blocks('Source map and reuse notes',[
 ('P / A / T / S · tract evidence','P01–P02: MassGIS assessor records and Dukes County registry index. A-series: MassGIS aerials and date verification. T1951/T1972: original USGS quadrangles. S01: EOX Sentinel-2 annual mosaic.'),
 ('D / H · historical context','D-series: Digital Commonwealth records, with repository metadata and native IIIF scans. H-series: Harvard Forest map reproductions. Original resolution and geographic scope differ; see individual catalog entries.'),
 ('N / R · reporting and retrieval leads','N-series: Vineyard Gazette reporting, with one short headline screenshot. R-series: official histories, repository finding aids and records not acquired in full. Modern newspaper articles remain with the publisher.'),
 ('No blanket license for the cache','USGS maps are public domain. Other items retain their stated rights. The Foster aerial is CC BY-NC-ND 4.0; the EOX satellite and its derived plate are CC BY-NC-SA 4.0. The chapel photograph’s rights are unevaluated. Consult each entry before republication.'),
 ('Find every source and verify the files','05_Research_Catalog/source_catalog.csv and source_catalog.json contain direct URLs, scope, status, notes and rights. Metadata and acquisition logs are included. SHA256SUMS.txt provides a checksum for every other packaged file.')])
cv.save()
shutil.copy2(OUT,B/OUT.name)
shutil.copy2(__file__,C/'build_collection.py')

# Verify all catalogued acquired paths, then hash the complete package except the hash file itself.
for r in catalog:
    for p in r['files']:
        if not (B/p).is_file():raise FileNotFoundError(p)
manifest=[]
for p in sorted(B.rglob('*')):
    if p.is_file() and p.name!='SHA256SUMS.txt':
        manifest.append(hashlib.sha256(p.read_bytes()).hexdigest()+'  '+rel(p))
(C/'SHA256SUMS.txt').write_text('\n'.join(manifest)+'\n')
print(json.dumps({'pdf':str(OUT),'pdf_pages':pagecount,'catalog_sources':len(catalog),'packaged_files':len(manifest)+1,'pdf_megabytes':round(OUT.stat().st_size/1e6,2)},indent=2))
