#!/usr/bin/env python3
"""Generate entity-specific AVOWAL inquiry/request letters and render full PDFs."""
from pathlib import Path
import html, re, subprocess, shutil, json
import fitz

ROOT = Path('/Users/icloudabe/GLAS_Rosenwald_Deep_Dive/JOINT_INQUIRY_PACKAGE')
OUT = ROOT / 'ENTITY_LETTERS_AVOWAL'
HTMLDIR = OUT / 'html'
MDDIR = OUT / 'markdown'
PDFDIR = OUT / 'pdf'
DOCXDIR = OUT / 'docx'
for d in [OUT, HTMLDIR, MDDIR, PDFDIR, DOCXDIR]: d.mkdir(parents=True, exist_ok=True)
CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
PANDOC = shutil.which('pandoc') or '/opt/homebrew/bin/pandoc'
DISC_FONT = '/Users/icloudabe/aria/avowal_brand/fonts/DMMono-Regular.ttf'
DATE = 'July 10, 2026'
CHANNEL = 'VIA EMAIL & CERTIFIED U.S. MAIL'
PHONE = '(203) 391-1041'
EMAIL = 'abe@avowal.ai'
ADDRESS = '1127 High Ridge Road, Suite 151'
CITY = 'Stamford, CT 06905'
DISCLAIMER = ('This letter was prepared by a self-represented party using the ELARIA Document Engine. '
              'AVOWAL is a technology platform, not a law firm; ELARIA is an AI operations agent, not legal counsel; '
              'neither provides legal advice. Use of AVOWAL does not create an attorney-client relationship.')

WORDMARK = '''<svg viewBox="0 0 360 100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="AVOWAL — Powered by ELARIA">
<g transform="translate(10, 28)"><path d="M20 4 L36 34 L28 34 L20 18 L12 34 L4 34 Z" fill="none" stroke="#050a1a" stroke-width="2" stroke-linejoin="round"/><circle cx="20" cy="26" r="2.5" fill="#00d4ff"/></g>
<text x="62" y="52" style="font-family:'Bebas Neue',sans-serif;font-size:36px;letter-spacing:6.5px;fill:#050a1a;">AVOWAL</text>
<text x="62" y="74" style="font-family:'DM Mono',monospace;font-size:11px;letter-spacing:2.4px;fill:#3a4a6a;">POWERED BY ELARIA</text></svg>'''

COMMON_OPEN = [
    "I write in good faith to request information, records, and clarification concerning the relationships among Dalton Investments, Rosenwald Capital Management, Kings Bay, Rosenwald Partners, Beach Front, and Glass House Brands. This is a broad inquiry because the publicly disclosed ownership, financing, personnel, family, advisory, real-estate, insurance, and governance relationships cross entity lines.",
    "This letter does not accuse any person or entity of misconduct. It asks you to confirm, correct, or explain my understanding and to provide the records that permit an informed assessment. Where I rely on first-hand experience rather than a public filing, I say so expressly.",
    "Please respond within 21 days. If you cannot complete the response in that period, identify what you can provide, designate a response coordinator, and give a firm production schedule. If a premise is wrong, please state the correction and provide the record that resolves it."
]

PRESERVE = [
    "Preserve all responsive documents and electronically stored information from January 1, 2017 to the present, including email, text messages, Signal and WhatsApp messages, calendars, visitor logs, cloud drives, accounting systems, cap tables, board portals, deal rooms, compliance systems, trade records, and personal devices used for business.",
    "Identify the custodians, systems, accounts, archives, and date ranges searched.",
    "For any withheld document, provide a log stating its date, sender, recipients, general subject, custodian, and the basis for withholding.",
    "If a responsive record is held by an affiliate, administrator, custodian, broker, auditor, law firm, regulator, or service provider, identify that holder and request the record or authorize its release.",
    "Produce records electronically in native format where available, with searchable text and ordinary metadata preserved. Rolling production is welcome.",
]

POSITIONS = [
    "Identify every Glass House or GH Group security or economic interest held from January 1, 2017 to the present by the entity, its affiliates, private funds, advised accounts, directors, officers, control persons, employees, trustees, or immediate-family vehicles.",
    "Include common, multiple-voting, exchangeable, and preferred shares; warrants; options; convertible and promissory notes; loans; derivatives; guarantees; participation interests; and rights to conversion, dividends, sale proceeds, or liquidation proceeds.",
    "For each position, identify the legal holder, beneficial owner, adviser, custodian, source of funds, acquisition date and cost, voting and dispositive authority, conversion history, disposition, proceeds, and current status.",
    "Identify positions held by Sarah Alfandari, Steven D. Persky or Persky Financial Management, Janet Hunpadongrat, Christopher Ha, Anita Vora, and related family or investment vehicles; confirm or correct my understanding that each has had Glass House investment or financial involvement.",
    "Provide relevant Code of Ethics reports, annual holdings reports, transaction reports, preclearances, restricted-list or watch-list entries, conflicts analyses, and outside-business-activity approvals, with unrelated personal information redacted.",
    "Explain why a public Dalton 13F is or is not an adequate measure of the network's exposure, considering private funds, personal accounts, trusts, preferred securities, debt, derivatives, foreign or exchangeable securities, and related persons.",
]

KINGS = [
    "Confirm whether current Kings Bay Investment Co. Ltd., historic KBIC, and Kings Bay Capital Management Ltd. are the same entity, successors, assignor/assignee entities, or entities under common ownership or management.",
    "Identify Kings Bay's seven beneficial owners, or at minimum their categories and percentages, and identify each RCM or related person included in the approximately 86% related-person ownership reported in the current Form ADV.",
    "Produce the original Magu Farm note, co-lending agreement, KBIC-to-KBCM assignment, April 2020 novation/modification, security agreement, UCC records, conversion notice, preferred-share ledger, and UCC-3 termination.",
    "Reconcile the approximately $1.925 million principal, 6% interest, March 2023 maturity, accrued interest, and June 29, 2021 conversion into preferred shares.",
    "Identify every Dalton or RCM person who advised, approved, administered, booked, valued, custodied, traded, monitored, or exercised authority over the Glass House investment.",
    "Explain the SEDI reporting of Glass House securities through Kings Bay under JBR III's control or direction and the December 2025 liquidation to zero, including decision makers, instructions, trades, proceeds, recipients, and trading restrictions.",
    "State whether proceeds were distributed, loaned, reinvested, or transferred to RCM, Dalton, a Rosenwald trust, a Beach Front entity, a Glass House insider, or a family member.",
]

BEACH = [
    "Provide complete ownership and control records for Beach Front Properties LLC and Beach Front Property Management Inc. from 2017 to the present, including cap tables, operating agreements, shareholder ledgers, Statements of Information, and amendments.",
    "Identify every Glass House founder, director, officer, family trust, RCM client, Dalton person, Kings Bay owner, or related person with an interest in either Beach Front entity or an affiliated real-estate vehicle.",
    "Describe shared personnel, offices, vendors, systems, accounting, legal, finance, insurance, real estate, capital formation, and services between Beach Front and Glass House.",
    "Produce the September 28, 2020 consulting agreement, amendments, statements of work, invoices, work product, time records, payment ledger, pricing support, approvals, and recusals.",
    "Produce the Beach Front $2 million note, 15% interest terms, conversion documents, preferred-share ledger, dividends, redemptions, and disposition records.",
    "Identify every Beach Front-managed landlord, lender, consultant, insurer, investor, seller, or service provider that transacted with Glass House, and provide beneficial ownership, amounts, approvals, recusals, bids, appraisals, and current status.",
    "Explain whether the Glass House audit committee and auditor reviewed the Beach Front relationships as one integrated network or each entity in isolation.",
    "Identify controls that prevent commingling of personnel, information, expenses, opportunities, and decision making if Beach Front and Glass House are operationally separate.",
]

GLAS_BOARD = [
    "Produce the current related-party master list and identify the persons and percentages behind every financial-statement description such as 'partially owned by an executive or board member' or 'majority owned by an executive and certain directors.'",
    "Explain how the board evaluated Jocelyn Rosenwald's Rule 10A-3 independence given that she is JBR III's daughter, a Glass House co-founder and shareholder, an RCM director, a Dalton director, a former Beach Front executive, and the namesake of an RCM-advised Glass House-holding trust.",
    "Produce the NYSE foreign-private-issuer affirmation, independence questionnaires, counsel memoranda, compensation and affiliate analyses, recusal records, and board determination.",
    "Identify the related persons who supplied approximately $13 million in Series E consideration and received approximately $1.5 million in preferred dividends in 2025; produce subscriptions, allocations, terms comparisons, fairness materials, approvals, and recusals.",
    "Explain whether Kings Bay's RCM management, concentrated related-person ownership, note, conversion, preferred interest, common shares, and liquidation were presented to the audit committee as one continuous relationship.",
    "Identify every Dalton, RCM, Beach Front, Kings Bay, or family person who assisted with Glass House finances, treasury, accounting, cap tables, controls, investor reporting, disclosures, or related-party identification.",
    "Produce related-party controls, annual questionnaires, vendor/entity beneficial-owner screening, journal-entry review, and audit-committee monitoring records during the unresolved ITGC material weakness.",
]

ASC810 = [
    "Produce the complete ASC 810 consolidation/deconsolidation and VIE memoranda, including substantive equity at risk, power, economics, protective versus participating rights, related parties, de facto agents, common control, and reconsideration events.",
    "Produce the NSJB Purchase Note, Consulting or Management Services Agreement, repurchase and put-note forms, all schedules and statements of work, side letters, escrow records, lender consent, indemnities, guarantees, working-capital commitments, tax-sharing arrangements, and DCC/local approvals.",
    "Identify NSJB's beneficial owners, capitalization, bank funding, source of funds, and every prior relationship with Glass House, Beach Front, Dalton, RCM, Kings Bay, the Rosenwald family, JML Law, or company insiders.",
    "Explain whether seller financing and the note-offset mechanism supplied substantive independent equity at risk.",
    "Reconcile Ex. 99.5's use of $29.935 million as 'net assets' with the same exhibit's removal of $25.016 million of liabilities.",
    "Produce final journal entries, valuation of the retained interest, actual closing accounting, auditor consultation or concurrence, audit-committee materials, and any correction or revision of the reported $11.415 million pro forma loss.",
]

DCC = [
    "Produce the complete citation-and-fine file for CCL21-0005116, including the citation, amount, findings, inspection evidence, service, corrective action, conference or hearing, appeal, settlement, payment, and finality.",
    "Produce all owner, financial-interest-holder, change-of-control, change-of-ownership, designated-responsible-party, license-modification, background, and approval records involving Glass House Retail, GHB Usub, Glass House Brands, NSJB, Beilke, Sarris, Dalton, RCM, Kings Bay, Rosenwald persons, and Beach Front persons or entities.",
    "Identify every investor, adviser, lender, noteholder, guarantor, consultant, service provider, or financial-interest holder disclosed to DCC but not identified in public securities filings.",
    "Produce premises-access, visitor, sign-in/sign-out, age verification, confidentiality, ownership, financial-interest, and compliance records relating to tours or visits by Dalton, RCM, Kings Bay, Beach Front, investors, or family guests.",
]

letters = [
{
'id':'01_DALTON_INVESTMENTS','recipient':'Sarah Alfandari, CEO and President\nChristopher Ha, CCO and Counsel\nJanet Hunpadongrat, COO and CFO\nJames B. Rosenwald III, Chairman and CIO','firm':'Dalton Investments, Inc.','street':'360 N. Pacific Coast Highway, Suite 1060','city':'El Segundo, CA 90245','salutation':'Dear Ms. Alfandari, Mr. Ha, Ms. Hunpadongrat, and Mr. Rosenwald','subject':'Broad inquiry and voluntary document request concerning Glass House investments, Kings Bay, RCM, Beach Front, shared personnel, compliance, and client exposure','email':'info@daltoninvestments.com',
'facts':['Current Form ADV identifies RCM as Dalton\'s majority owner and identifies Alfandari, Ha, Hunpadongrat, JBR III, and Jocelyn Rosenwald as senior personnel or directors.','In or around December 2022, I personally toured Glass House Farms with Ms. Alfandari, who brought a family member visiting from France. I understand that Ms. Alfandari, Steven Persky, Janet Hunpadongrat, and Christopher Ha invested in Glass House.'],
'sections':[('Investment and beneficial ownership',POSITIONS),('Farm tour and information access',[
"Confirm the date, site, attendees, host, authorizing person, business purpose, visitor records, and capacity in which Ms. Alfandari attended the Glass House Farms tour that occurred in or around December 2022. Please search at minimum November 1, 2022 through January 31, 2023 if the precise date cannot immediately be identified.",
"Identify the accompanying family member by relationship and role if privacy requires, and state whether the person was an investor, prospective investor, adviser, or guest.",
"Identify nonpublic operational, financing, licensing, forecast, transaction, or strategic information presented and all confidentiality or trading restrictions applied.",
"Identify trades or changes in Glass House positions by attendees within 60 days before or after the tour and provide compliance preclearance records.",
]),('Kings Bay',KINGS),('Shared personnel and finance',[
"Describe all Dalton personnel work for RCM, Glass House, GH Group, Kings Bay, Beach Front, or related entities, including informal assistance and secondments.",
"Identify Glass House bank, broker, custodian, financing, subscription, conversion, wire, valuation, accounting, forecast, cap-table, tax, board, or investor records accessed through Dalton people or systems.",
"Produce shared-services, books-and-records, archives, compliance, trading, accounting, administration, and fee-allocation agreements with RCM and affiliates.",
"Explain how conflicts were supervised when the same control persons, CCO, finance personnel, directors, and family interests crossed entities.",
]),('Preservation and production',PRESERVE)]},
{
'id':'02_RCM','recipient':'James B. Rosenwald III, President and Director\nLaura Parker Rosenwald, Executive Vice President and Trustee\nAnita Vora, CFO, Secretary and Treasurer\nChristopher Ha, Chief Compliance Officer','firm':'Rosenwald Capital Management, Inc.','street':'121 W. Torrance Boulevard, Suite 100','city':'Redondo Beach, CA 90277','salutation':'Dear Mr. and Mrs. Rosenwald, Ms. Vora, and Mr. Ha','subject':'Broad inquiry and voluntary document request concerning Kings Bay, Rosenwald Partners, Dalton, Beach Front, Glass House, trusts, and related-person conflicts','email':'info@daltoninvestments.com',
'facts':['Current RCM Form ADV identifies the Rosenwald Family Trust as controlling owner; JBR III, Laura, Jill, Jocelyn, Vora, and Ha as control or governance persons; Kings Bay and Rosenwald Partners as private funds; and Beach Front Properties as a related person.','I understand that Anita Vora and Christopher Ha performed functions affecting RCM and Glass House finances and invested in Glass House.'],
'sections':[('Ownership, governance, and shared services',[
"Produce RCM's current and historical capitalization, shareholder records, board minutes, bylaws, and the Rosenwald Family Trust control documents sufficient to establish voting and economic control.",
"Produce every shared-services, back-office, trading, compliance, records, email-archive, accounting, finance, and fee-allocation agreement with Dalton, Rising Sun, Beach Front, or other affiliates.",
"Identify all RCM personnel who performed any service for Glass House, GH Group, Kings Bay, Dalton, Beach Front, or NSJB.",
"Describe Anita Vora's and Christopher Ha's roles in Glass House financing, treasury, accounting, cap tables, wires, valuation, reporting, compliance, or investments.",
]),('Glass House exposure',POSITIONS),('Kings Bay',KINGS),('Rosenwald Partners',[
"Identify Rosenwald Partners' 48 beneficial owners, or their categories and percentages, and every GLAS/GH Group position, loan, note, derivative, guarantee, or related investment.",
"Produce LP registers, subscription documents, side letters, capital accounts, audited financials, position reports, trade blotters, related-party approvals, and loan or guarantee schedules.",
"Identify any Glass House insider, Dalton person, Beach Front person, family trust, foundation, or minor beneficiary with an interest.",
]),('Beach Front and related-person routing',BEACH),('Preservation and production',PRESERVE)]},
{
'id':'03_KINGS_BAY','recipient':'The Directors, Officers, Investment Manager, and Registered Office','firm':'Kings Bay Investment Company Ltd.','street':'c/o Cayman National Trust Co. Ltd., P.O. Box 30239, Suite 6201','city':'Camana Bay, Grand Cayman KY1-1201, Cayman Islands','salutation':'Dear Directors, Officers, and Authorized Representatives','subject':'Broad corporate, ownership, investment, financing, Glass House, and disposition-record request','email':'',
'facts':["RCM's current Form ADV reports Kings Bay as a Cayman private fund with seven beneficial owners and concentrated related-person ownership. Historic issuer and SEDI records connect Kings Bay to Glass House financing and securities."],
'sections':[('Corporate and beneficial ownership',[
"Produce certificates of incorporation and good standing, memorandum and articles, amendments, registers of directors/officers/members, beneficial-owner and KYC records, CIMA filings, and annual returns from 2017 to present.",
"Identify each beneficial owner's percentage, relationship to RCM, Dalton, the Rosenwald family, Beach Front, and Glass House, and source of invested capital.",
"Produce all investment-management, administration, custody, prime brokerage, valuation, audit, and advisory agreements, including all prior agreements with RCM or Dalton.",
]),('Glass House financing and securities',KINGS),('Financial statements and custody',[
"Produce audited financial statements, audit opinions, management letters, valuation policies, administrator reports, custodian statements, broker statements, and investor capital statements from 2017 to present.",
"Authorize JTC, PwC Cayman, Haywood, Morgan Stanley, Shore Capital, RCM, and any other service provider to confirm the Glass House positions and related records.",
]),('Preservation and production',PRESERVE)]},
{
'id':'04_ROSENWALD_PARTNERS','recipient':'Rosenwald Capital Management, Inc., General Partner\nThe Limited Partnership and its Authorized Representatives','firm':'Rosenwald Partners, L.P.','street':'121 W. Torrance Boulevard, Suite 100','city':'Redondo Beach, CA 90277','salutation':'Dear General Partner and Authorized Representatives','subject':'Broad beneficial-owner, Glass House exposure, related-party, loan, guarantee, and fund-record request','email':'',
'facts':['Current RCM Form ADV reports Rosenwald Partners as a Delaware private fund with approximately 48 beneficial owners and substantial related-person ownership. Public ADV data do not identify the investors or portfolio.'],
'sections':[('Ownership and fund records',[
"Produce the partnership agreement and amendments, GP records, limited-partner register, subscriptions, side letters, capital accounts, K-1 recipient schedule, audited financials, valuations, administrator and custodian reports, and distribution ledger from 2017 to present.",
"Identify all related persons, family members, trusts, foundations, minors, Dalton personnel, Beach Front persons, and Glass House insiders with interests.",
]),('Glass House and related exposure',POSITIONS + [
"Identify every loan, note, guarantee, support agreement, line of credit, capital commitment, or transfer involving Glass House, GH Group, Beach Front, Kings Bay, RCM, Dalton, or a Rosenwald trust.",
]),('Preservation and production',PRESERVE)]},
{
'id':'05_BEACH_FRONT_PROPERTIES','recipient':'Kyle Kazan, Agent, Manager, and Co-Founder\nJames B. Rosenwald III / Rosenwald Capital Management, identified management interests\nThe Managers and Members','firm':'Beach Front Properties, LLC','street':'3711 Long Beach Boulevard, Suite 814','city':'Long Beach, CA 90807','salutation':'Dear Mr. Kazan, Mr. Rosenwald, and Managers and Members','subject':'Broad ownership, Glass House, RCM, Dalton, real-estate, financing, consulting, and related-party record request','email':'',
'facts':['California and adviser records identify Beach Front Properties as an active entity and current related person of RCM and Dalton. Historic RCM filings identify numerous Beach Front-managed investment vehicles.'],
'sections':[('Ownership and organization',BEACH[:3]),('Glass House transactions',BEACH[3:]),('Portfolio and entities',[
"Produce a complete schedule of every Beach Front I-VIII, single-property, joint-venture, manager, member, landlord, lender, and operating entity from 1997 to present, with entity numbers, status, owners, managers, properties, debts, UCCs, and dispositions.",
"Identify all RCM clients, Dalton persons, Rosenwald trusts, Glass House persons, and Kazan trusts invested in the vehicles.",
"Produce operating agreements, subscriptions, capital accounts, K-1 schedules, property ledgers, title policies, loan files, guarantees, management agreements, and fee/promote calculations.",
]),('Preservation and production',PRESERVE)]},
{
'id':'06_BFPM','recipient':'Kyle Kazan, Founder and Chairman\nRobert Abbasi, Vice Chairman and Principal\nKris Hulgreen, Chief Operating Officer\nMargaret Holden, Chief Financial Officer','firm':'Beach Front Property Management Inc.','street':'1212 Long Beach Boulevard','city':'Long Beach, CA 90813','salutation':'Dear Mr. Kazan, Mr. Abbasi, Mr. Hulgreen, and Ms. Holden','subject':'Broad ownership, Glass House integration, consulting, finance, personnel, insurance, PPP, and related-party request','email':'',
'facts':['Glass House filings disclose recurring BFPM consulting for M&A, real-estate acquisition, and financing. Public biographies identify overlapping founder history, and public records describe BFPM ownership of or ties to an insurance broker used by Glass House.'],
'sections':[('Ownership and Glass House integration',BEACH),('Personnel and finance',[
"Identify every current or former employee, officer, accountant, finance professional, attorney, consultant, or contractor who performed work for both BFPM/BFP and Glass House or GH Group.",
"Produce intercompany allocations, expense reimbursements, payroll sharing, IT/system access, bank authority, accounting access, and service schedules.",
"Identify all farm, cannabis, investor, financing, insurance, licensing, and board-related work performed for Glass House.",
]),('PPP and financing records',[
"Produce BFPM's first- and second-draw PPP applications, certifications, payroll support, revenue-decline calculations, forgiveness applications, lender correspondence, and use-of-proceeds records.",
"Identify intercompany payments, loans, advances, guarantees, or shared expenses involving Glass House, RCM, Dalton, Kings Bay, or related persons during the covered periods.",
]),('Preservation and production',PRESERVE)]},
{
'id':'07_JON_A_NEU','recipient':'The President, Directors, Officers, and Owners','firm':'John A. Neu Insurance Services, Inc.','street':'4040 Palos Verdes Drive North, Suite 107','city':'Rolling Hills Estates, CA 90274','salutation':'Dear President, Directors, Officers, and Owners','subject':'Broad ownership, Glass House insurance placement, commissions, Beach Front relationship, and related-party record request','email':'',
'facts':['Glass House reports material annual insurance-brokerage expense to a Neu entity described as majority owned by a Beach Front entity, with inconsistent Beach Front entity naming across filings.'],
'sections':[('Ownership and control',[
"Produce formation records, bylaws, shareholder and beneficial-owner ledgers, officer/director registers, amendments, DBAs, producer licenses, appointments, and ownership-change filings from 2017 to present.",
"Identify every Beach Front, Kazan, Rosenwald, RCM, Dalton, Kings Bay, or Glass House ownership or compensation interest.",
"Reconcile whether Beach Front Properties LLC or Beach Front Property Management Inc. is the majority owner and identify dates and percentages.",
]),('Glass House business',[
"Produce all brokerage, consulting, risk-management, placement, renewal, claims, premium-financing, commission, fee, and service agreements with Glass House, GH Group, subsidiaries, farms, retail entities, landlords, or contractors.",
"Provide policy schedules, carriers, premiums, commissions, contingent compensation, overrides, referrals, invoices, payment ledgers, approvals, bids, market comparisons, and recusals.",
"Identify all services connected to the July 2025 raids, labor contractors, worker death, DCC citation, GHR transaction, and related claims or coverage notices.",
]),('PPP records',[
"Produce the 2020 PPP application, eligibility certifications, payroll support, forgiveness application, lender correspondence, and use-of-proceeds records.",
]),('Preservation and production',PRESERVE)]},
{
'id':'08_GLASS_HOUSE_BOARD','recipient':'Benjamin Vega, General Counsel and Corporate Secretary\nKyle Kazan, Chairman and CEO\nJocelyn Rosenwald, Audit Committee Chair\nHumble Lukanga and Hector De La Torre, Audit Committee Members\nThe Board of Directors and Audit Committee','firm':'Glass House Brands Inc.','street':'3645 Long Beach Boulevard','city':'Long Beach, CA 90807','salutation':'Dear Mr. Vega, Mr. Kazan, Ms. Rosenwald, Mr. Lukanga, Mr. De La Torre, and Directors','subject':'Broad board and audit-committee inquiry concerning related parties, Dalton/RCM/Kings Bay, Beach Front, personal investments, controls, NSJB, and disclosure','email':'ir@glasshousebrands.com; info@glasshousebrands.com',
'facts':['Glass House filings disclose extensive founder-linked consulting, financing, insurance, leases, preferred equity, and related-party transactions. First-hand information identifies additional Dalton senior personnel investments and a Glass House Farms tour attended by Dalton CEO Sarah Alfandari in or around December 2022.'],
'sections':[('Board, audit committee, and disclosure',GLAS_BOARD),('Complete investment accounting',POSITIONS),('Farm tours and information controls',[
"Produce visitor logs, approvals, sign-in records, host records, confidentiality agreements, tour materials, and attendee lists for Dalton, RCM, Kings Bay, Beach Front, investor, lender, or family visits from 2017 to present.",
"Confirm the Glass House Farms tour attended in or around December 2022 by Sarah Alfandari, me, and her family guest visiting from France; identify the precise date, site, hosts, purpose, information shared, and trading restrictions. Please search at minimum November 1, 2022 through January 31, 2023.",
"Identify any attendee position changes within 60 days before or after a visit and applicable preclearance or blackout controls.",
]),('Kings Bay and Beach Front',KINGS + BEACH),('NSJB and ASC 810',ASC810),('Regulatory and licensing',DCC),('Preservation and production',PRESERVE)]},
{
'id':'09_MGO','recipient':'Glass House Engagement Partner\nPublic Company Audit Practice Leadership','firm':'Macias Gini & O’Connell LLP (MGO)','street':'111 Pacifica, Suite 300','city':'Irvine, CA 92618-3705','salutation':'Dear Glass House Engagement Partner and Audit Practice Leadership','subject':'Voluntary accounting and audit inquiry concerning ASC 810, ASC 850, Rule 10A-3, related-party completeness, ITGCs, Kings Bay, Beach Front, and NSJB','email':'',
'facts':['MGO has served as Glass House auditor since 2020. Public filings identify an unresolved ITGC material weakness and a June 2026 deconsolidation resting on significant judgments and unfiled agreements.'],
'sections':[('Scope and independence',[
"Confirm the periods and services for which MGO served Glass House and provide engagement letters, non-audit-service schedules, fee approvals, and Rule 2-01 independence communications to the audit committee.",
"Identify all relationships considered in assessing audit-committee member independence and MGO independence, including Beach Front, RCM, Dalton, Kings Bay, and family entities.",
]),('ASC 810 deconsolidation',ASC810),('Related parties and controls',[
"Describe audit procedures over related-party completeness, counterparty beneficial ownership, insider questionnaires, vendor/entity masters, journal entries, leases, preferred financing, consulting, insurance, and note conversions.",
"Explain how the unresolved ITGC weakness affected audit evidence over revenue, inventory, related parties, and the systems used for the GHR transaction.",
"Confirm whether Kings Bay's RCM management and concentrated related-person ownership were considered in the issuer's related-party disclosures.",
"Identify audit differences, proposed adjustments, control deficiencies, significant risks, and communications relating to the matters in this letter, without disclosing privileged material if a lawful basis applies.",
]),('Preservation and production',PRESERVE)]},
{
'id':'10_NSJB','recipient':'Jared Beilke and Nicholas Sarris, Managers\nThe Members and Authorized Representatives','firm':'NSJB Investments LLC','street':'5855 Topanga Canyon Boulevard, Suite 300','city':'Woodland Hills, CA 91367','salutation':'Dear Mr. Beilke, Mr. Sarris, Members, and Authorized Representatives','subject':'Broad beneficial-owner, source-of-funds, independence, Glass House Retail, Purchase Note, services, and regulatory record request','email':'',
'facts':['NSJB was formed shortly before the June 2026 transaction, obtained all voting units and a 10% economic interest through a seller-financed Purchase Note, and appointed two of three GHR managers.'],
'sections':[('Formation, ownership, and independence',[
"Produce articles, Statements of Information, operating agreement, amendments, member and manager registers, subscriptions, capital accounts, beneficial-owner/KYC records, tax elections, and bank records from formation to present.",
"Identify source and amount of every capital contribution and whether any capital came from Glass House, GH Group, GHR, Beach Front, Dalton, RCM, Kings Bay, JML Law, a founder, family member, lender, or guarantor.",
"Identify every prior professional, personal, community, client, legal, financial, or business relationship with Glass House, Kazan, Farrar, Rosenwald persons, Dalton, RCM, Kings Bay, Beach Front, MGO, or company counsel.",
"Produce conflicts checks, waivers, engagements, communications, diligence, and independence certifications.",
]),('Transaction documents and operations',ASC810),('Cannabis approvals',DCC[1:]),('Preservation and production',PRESERVE)]},
{
'id':'11_GHR_GHB_USUB','recipient':'The Managers, Officers, Members, and Authorized Representatives','firm':'Glass House Retail, LLC and GHB Usub, LLC','street':'3645 Long Beach Boulevard','city':'Long Beach, CA 90807','salutation':'Dear Managers, Officers, Members, and Authorized Representatives','subject':'Broad membership, financing, services, control, operations, licensing, and intercompany record request','email':'ir@glasshousebrands.com',
'facts':['The June 2026 agreements allocate voting units to NSJB and retained exchangeable units to GHB Usub while preserving consent, service, call/put, conversion, information, and economic rights.'],
'sections':[('Membership and governance',[
"Produce member ledgers, manager appointments, resolutions, minutes, consents, budgets, officer appointments, delegations, committees, voting records, and all governance communications.",
"Identify every person who directs budgets, staffing, pricing, procurement, cash, inventory, compliance, licensing, leases, insurance, IT, payroll, financing, and strategic decisions.",
]),('ASC 810 and agreements',ASC810),('Intercompany transactions',[
"Produce every service, supply, cultivation, inventory, distribution, IP, brand, data, employee, lease, insurance, tax, cash-management, credit, guarantee, indemnity, and working-capital arrangement with GLAS, GH Group, Beach Front, Dalton, RCM, Kings Bay, or related persons.",
"Provide general ledgers, bank authority, intercompany accounts, invoices, payment ledgers, transfer-pricing support, and post-closing transactions.",
]),('Licensing',DCC[1:]),('Preservation and production',PRESERVE)]},
{
'id':'12_JML_LAW','recipient':'Nicholas Sarris and Jared Beilke, Managing Partners\nConflicts and Records Custodian','firm':'JML Law, APLC','street':'5855 Topanga Canyon Boulevard, Suite 300','city':'Woodland Hills, CA 91367','salutation':'Dear Mr. Sarris, Mr. Beilke, and Records Custodian','subject':'Voluntary inquiry concerning NSJB formation, conflicts, engagements, source of funds, Glass House relationships, and document custody','email':'',
'facts':['NSJB uses the JML Law business address and its managers are JML attorneys. The inquiry does not seek privileged legal advice; it seeks nonprivileged facts concerning identity, roles, conflicts, ownership, funding, and document custody.'],
'sections':[('Engagements and conflicts',[
"Identify every current or former client relationship between JML or its lawyers and Glass House, GH Group, GHR, GHB Usub, Beach Front, Dalton, RCM, Kings Bay, the Rosenwald family, Kyle Kazan, Graham Farrar, MGO, or their affiliates.",
"Produce nonprivileged engagement metadata, conflicts-check results, waivers, billing-party identity, payment source, and dates and general subject of representation.",
"State whether JML formed NSJB, drafted its operating agreement, provided its office, held funds, introduced parties, negotiated the transaction, or advised any transaction participant.",
"Identify NSJB's members and source of capital, or identify the custodian with authority to provide that information.",
]),('Role in GHR transaction',[
"Describe Beilke's and Sarris's roles as NSJB managers and GHR managers, compensation, fiduciary duties, time commitment, decision authority, and reporting arrangements.",
"Produce nonprivileged communications and records reflecting manager appointments, source of funds, independence certifications, regulatory submissions, and business decisions.",
]),('Preservation and production',PRESERVE)]},
{
'id':'13_JTC_CAYMAN','recipient':'The Managing Director, Compliance Officer, and Fund Administrator','firm':'JTC Fund Services (Cayman) Ltd.','street':'Grand Cayman','city':'Cayman Islands','salutation':'Dear Managing Director, Compliance Officer, and Fund Administrator','subject':'Voluntary fund-administration confirmation request concerning Kings Bay ownership, Glass House positions, valuation, custody, and distributions','email':'',
'facts':["RCM's current Form ADV identifies JTC Cayman as Kings Bay administrator and reports concentrated related-person ownership and historic Glass House exposure."],
'sections':[('Administration and ownership',[
"Confirm the dates and scope of JTC's engagement and produce or confirm fund identifiers, constitutional records, directors, authorized signatories, investor categories and percentages, and administrator agreements.",
"Confirm the seven beneficial-owner count and the reported related-person and non-U.S. ownership percentages, subject to lawful confidentiality limits.",
]),('Glass House records',[
"Confirm Kings Bay's Glass House notes, preferred shares, common or exchangeable shares, conversions, valuations, sales, proceeds, and distributions from 2017 to present.",
"Identify custodians, brokers, pricing sources, valuation reviewers, and accounts receiving December 2025 sale proceeds.",
"Provide administrator reports, capital statements, transaction ledgers, NAV workpapers, and audit support relating to Glass House.",
]),('Preservation and production',PRESERVE)]},
{
'id':'14_SEC_FOIA','recipient':'FOIA Office','firm':'U.S. Securities and Exchange Commission','street':'100 F Street, N.E.','city':'Washington, DC 20549','salutation':'Dear FOIA Officer','subject':'FOIA request — Dalton, RCM, Kings Bay, related-person reporting, Glass House disclosures, examinations, correspondence, and succession records','email':'',
'facts':['This request seeks agency records and should be construed broadly. It recognizes applicable FOIA exemptions and requests all segregable nonexempt material.'],
'sections':[('Entities and period',[
"Search January 1, 1997 to present for Dalton Investments LLC (CRD 109538), Dalton Investments, Inc. (CRD 308609), RCM (CRDs 104630 and 290118), Rising Sun Management, Kings Bay Investment Co., Kings Bay Capital Management, Rosenwald Partners, Beach Front Properties, Beach Front Property Management, JBR III, Jocelyn Rosenwald, Sarah Alfandari, Steven Persky, Christopher Ha, Janet Hunpadongrat, and Anita Vora.",
]),('Requested SEC records',[
"Produce registration, succession, withdrawal, termination, umbrella/relying-adviser, ownership-change, and amendment correspondence and staff notes.",
"Produce publicly releasable examination existence/date information, closing letters, deficiency letters, responses, undertakings, remediation, enforcement referrals that produced public action, and public orders or releases.",
"Produce records concerning Form ADV accuracy, related persons, custody, valuation, private funds, personal trading, outside activities, shared services, record locations, Kings Bay, Rosenwald Partners, and Beach Front.",
"Produce EDGAR filing-review and comment correspondence concerning Glass House related parties, Kings Bay, RCM, Dalton, Beach Front, Jocelyn independence, ASC 810, GHR/NSJB, pro formas, ITGCs, and the NYSE uplisting.",
"Produce communications with NYSE, PCAOB, Canadian regulators, DCC, or other agencies concerning those subjects, to the extent releasable.",
]),('FOIA processing',[
"Produce all reasonably segregable portions, identify exemptions, provide a Vaughn-style index sufficient to evaluate withholding, provide rolling productions, and contact me before denying or materially narrowing the request.",
"Provide advance notice before fees exceed $100 and consider a fee waiver or limitation because the request concerns public-company and adviser disclosure and governance.",
])]},
{
'id':'15_NFA','recipient':'Information Center and Legal/Compliance Records','firm':'National Futures Association','street':'300 S. Riverside Plaza, Suite 1800','city':'Chicago, IL 60606','salutation':'Dear Information Center and Records Custodian','subject':'Public-record request — Dalton Investments, NFA Case 06-BCC-012, seven pools, final decision, and compliance disposition','email':'',
'facts':['Historical Form ADV materials disclose an NFA action concerning late annual reports for seven pools, a $10,000 settlement, and an October 12, 2006 final decision.'],
'sections':[('Requested records',[
"Produce the complaint, notice, case number, case docket, seven pool names, annual reports and due dates, correspondence, offer of settlement, final decision, fine/payment record, compliance follow-up, and public disciplinary history.",
"Identify the respondent's exact legal name, NFA IDs, principals, associated persons, CPO/CTA registrations, and successor/predecessor treatment.",
"Produce any publicly available later matter involving Dalton, RCM, RCM personnel, the named pools, or successor entities.",
]),('Processing',[
"If records are online, provide stable links and document identifiers. If any portion is unavailable, identify the reason and custodian.",
])]},
{
'id':'16_CA_SOS','recipient':'Business Programs Division — Business Entities','firm':'California Secretary of State','street':'1500 11th Street','city':'Sacramento, CA 95814','salutation':'Dear Business Programs Division Records Custodian','subject':'Certified entity-history and document-image request — Beach Front, Glass House, NSJB, related real-estate, insurance, and adviser entities','email':'',
'facts':['This request seeks certified public business-entity records and complete filing histories.'],
'sections':[('Entity names',[
"Search exact names, punctuation variants, former names, and begins-with results for Beach Front Properties LLC; Beach Front Property Management Inc.; Beach Front I-VIII; 24818 Eshelman; 23330 Arlington; Lamlex; 1223 Anaheim Street; NPI B.F. Ventures; Park Rolling Hills; Beach Vault; Beach Front Vintage 2014; Beach Front Diversified Investments; 930 N Unruh; Beach Front Waterford joint ventures; Jon/John A. Neu Insurance; 3645 Long Beach; Neo Street Partners; Isla Vista GHG; 5042 Real Estate Investment; 2000 De La Vina; GH Group; Glass House Retail; GHB Usub; NSJB Investments; JML Law; and every related entity returned by manager, agent, or address searches.",
]),('Requested certified records',[
"For each entity, provide certified formation documents, Statements of Information, amendments, mergers, conversions, cancellations, suspensions, revivals, agent changes, officer/manager/member disclosures, addresses, status history, labor-judgment disclosures, and all filed images and metadata from inception to present.",
"Provide an official search certificate identifying no-record results and close variants.",
]),('Processing',[
"Contact me with fees and ordering instructions before processing if advance payment is required. Electronic certified copies are preferred where available.",
])]},
{
'id':'17_CA_UCC','recipient':'Uniform Commercial Code Section','firm':'California Secretary of State','street':'1500 11th Street','city':'Sacramento, CA 95814','salutation':'Dear UCC Records Custodian','subject':'Certified UCC, judgment-lien, and state-tax-lien debtor-name searches — Beach Front, Glass House, Dalton, RCM, Kings Bay, NSJB, and related entities','email':'',
'facts':['Official portal searches identified financing-statement leads but do not replace certified searches or complete filing images.'],
'sections':[('Search scope',[
"Conduct certified searches from January 1, 1997 to present under every entity named in the companion business-entity request, plus Dalton Investments LLC, Dalton Investments Inc., RCM, Rosenwald Partners, Kings Bay Investment Co., Kings Bay Capital Management, Glass House Brands, GH Group, GHR, GHB Usub, NSJB, and exact punctuation or former-name variants.",
]),('Requested records',[
"Provide search certificates and all active, lapsed, terminated, archived, assigned, continued, amended, state-tax-lien, and judgment-lien records.",
"Provide every UCC-1, amendment, continuation, assignment, termination, information statement, collateral exhibit, debtor-address history, secured-party record, fixture-filing reference, and filing metadata.",
"Include the known or potential BFP/F&M, BFPM/WebBank, 24818 Eshelman/Fannie Mae, 23330 Arlington/JPMorgan, and Kings Bay UCC-3 records.",
]),('Processing',[
"Contact me with fees and ordering instructions before processing. Certified electronic results are preferred.",
])]},
{
'id':'18_DCC','recipient':'Public Records Coordinator and Licensing Division','firm':'California Department of Cannabis Control','street':'2920 Kilgore Road','city':'Rancho Cordova, CA 95670','salutation':'Dear Public Records Coordinator and Licensing Division','subject':'California Public Records Act request — Glass House citation, ownership, financial interests, farm tours, GHR/NSJB approvals, and related-person records','email':'publicrecords@cannabis.ca.gov',
'facts':['This request seeks agency records concerning a public citation, licensing ownership and financial interests, visitor/access controls, and the June 2026 ownership transaction.'],
'sections':[('Citation and compliance action',[DCC[0]]),('Ownership, financial interests, and approvals',DCC[1:]),('Additional records',[
"Produce communications with Glass House, counsel, auditors, NYSE, SEC, DOL, DHS/ICE/HSI/CBP, Cal/OSHA, local agencies, investors, lenders, and farm labor contractors concerning the requested matters.",
"Produce application checklists, deficiency notices, background/suitability materials, organizational charts, cap tables, source-of-funds records, approval/denial/acknowledgment letters, and conditions or waivers.",
]),('CPRA processing',[
"Construe the request broadly; produce all segregable nonexempt portions electronically; identify exemptions and provide an adequate withholding log; provide rolling production; and contact me before denying, closing, or materially narrowing the request.",
])]},
{
'id':'19_NYSE','recipient':'NYSE Regulation — Listed Company Compliance','firm':'New York Stock Exchange','street':'11 Wall Street','city':'New York, NY 10005','salutation':'Dear Listed Company Compliance and Records Custodian','subject':'Inquiry and records request — GLAS listing review, FPI affirmation, Rule 10A-3, §314 related parties, ASC 810 deconsolidation, and disclosure correspondence','email':'',
'facts':['GLAS began NYSE trading after a June 2026 deconsolidation and submitted an FPI governance affirmation/certification. The request recognizes that some exchange regulatory records may be confidential.'],
'sections':[('Requested records and clarification',[
"Provide publicly releasable listing application, certification, FPI corporate-governance affirmation, governance-differences materials, deficiency or cure notices, and correspondence concerning GLAS.",
"Provide correspondence or issue summaries concerning Rule 10A-3 audit-committee independence, Jocelyn Rosenwald, founder/family relationships, Dalton/RCM/Kings Bay, Beach Front, related-party oversight under §314, and the unresolved ITGC weakness.",
"Provide correspondence concerning the GHR/NSJB deconsolidation, ASC 810, seller financing, retained economics, missing agreements, adult-use versus medical cannabis, DCC approvals, and continued-listing conditions.",
"Identify the rules or policies governing public access to these records and any available appeal or reconsideration path for withheld material.",
]),('Processing',[
"If NYSE is not subject to FOIA for these records, treat this as a voluntary transparency request and produce any material that can lawfully be disclosed.",
"If SEC holds responsive exchange submissions, identify the form, date, and SEC filing or contact through which they may be requested.",
])]},
{
'id':'20_PWC_CAYMAN','recipient':'Kings Bay Audit Engagement Partner and Records Custodian','firm':'PricewaterhouseCoopers, Cayman Islands','street':'Georgetown','city':'Grand Cayman, Cayman Islands','salutation':'Dear Kings Bay Audit Engagement Partner and Records Custodian','subject':'Voluntary audit-confirmation request concerning Kings Bay ownership, Glass House investments, valuation, custody, and distributions','email':'',
'facts':["RCM's Form ADV identifies PwC Cayman as Kings Bay auditor. This request does not claim PwC owes a duty to the requester and does not seek privileged legal advice."],
'sections':[('Engagement and audit scope',[
"Confirm the years PwC audited Kings Bay, the accounting framework, scope, audit opinions, and whether reports were distributed to investors.",
"Confirm whether audit procedures covered beneficial ownership, related persons, the Glass House note, preferred conversion, common-share positions, custody, valuation, December 2025 sales, proceeds, and distributions.",
"Identify any qualified opinion, emphasis, material weakness, significant deficiency, related-party issue, valuation issue, or audit adjustment concerning those matters, to the extent lawfully disclosable.",
"Request authorization from Kings Bay/RCM to release the audited financial statements and relevant confirmations, or identify the person who can provide authorization.",
]),('Preservation',PRESERVE)]},
]

# Helpers

def md_inline(s):
    e = html.escape(s)
    e = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', e)
    e = re.sub(r'\*(.+?)\*', r'<em>\1</em>', e)
    return e

def body_markdown(L):
    out=[]
    for p in COMMON_OPEN: out.append(p+'\n')
    out.append('## Basis for inquiry\n')
    for f in L['facts']: out.append('- '+f)
    out.append('\n')
    n=1
    for heading, items in L['sections']:
        out.append(f'## {heading}\n')
        for item in items:
            out.append(f'{n}. {item}')
            n += 1
        out.append('')
    out.append('## Closing\n')
    out.append('I welcome straightforward explanations and corrections. Please do not answer only for the formal legal entity if responsive information is held by an affiliate or service provider. The purpose is to obtain a coherent account of the relationships and the records needed to understand who invested, who advised, who controlled, who was paid, who approved each transaction, and what was disclosed to clients, investors, auditors, exchanges, and regulators.\n')
    return '\n'.join(out), n-1

def to_html(md):
    return subprocess.run([PANDOC,'-f','markdown','-t','html','--wrap=none'],input=md,text=True,capture_output=True,check=True).stdout

def render_html(L, body_html, req_count):
    rec = '<br/>'.join(md_inline(x) for x in L['recipient'].split('\n'))
    email_line = f'<br/><span class="email">Email: {html.escape(L["email"])}</span>' if L.get('email') else ''
    sig_html = '<img class="wetsig" src="file:///Users/icloudabe/law_firm_associations/abe_signature.png"/>'
    body_class = 'ultracompact' if L['id'] in {'11_GHR_GHB_USUB','18_DCC'} else ('compact' if L['id'] in {'14_SEC_FOIA','15_NFA','16_CA_SOS','17_CA_UCC','19_NYSE','20_PWC_CAYMAN'} else '')
    return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>AVOWAL — {html.escape(L['firm'])} Inquiry</title>
<style>
@font-face{{font-family:"Bebas Neue";src:url("../../../fonts/BebasNeue-Regular.ttf")}}@font-face{{font-family:"EB Garamond";src:url("../../../fonts/EBGaramond-VF.ttf");font-weight:400 700}}@font-face{{font-family:"EB Garamond";src:url("../../../fonts/EBGaramond-Italic-VF.ttf");font-style:italic;font-weight:400 700}}@font-face{{font-family:"DM Mono";src:url("../../../fonts/DMMono-Regular.ttf")}}@font-face{{font-family:"Outfit";src:url("../../../fonts/Outfit-VF.ttf");font-weight:300 700}}
:root{{--navy:#050a1a;--surface:#f4f7fc;--cyan:#00d4ff;--cyan-ink:#0089a8;--gold:#f0b429;--gold-ink:#9a7212;--ink:#1d2336;--ink-dim:#51607a;--ink-xdim:#8693a8;--display:"Bebas Neue",sans-serif;--serif:"EB Garamond",Georgia,serif;--mono:"DM Mono",monospace}}
*{{box-sizing:border-box;margin:0;padding:0}}@page{{size:Letter;margin:.62in .72in 1.02in .86in;background:linear-gradient(90deg,var(--cyan) 0,var(--cyan) 7px,#fff 7px,#fff 100%)}}body{{font-family:var(--serif);font-size:10px;line-height:1.42;color:var(--ink);padding-left:8px}}.rail{{display:none}}
.pgfoot{{position:fixed;bottom:-.79in;left:0;right:0;font-family:var(--mono);font-size:5.7px;line-height:1.2;color:var(--ink-dim);border-top:.75px solid rgba(5,10,26,.12);padding-top:4px;min-height:.38in;background:#fff}}.pgfoot .site{{color:var(--cyan-ink)}}
header{{display:flex;justify-content:space-between;align-items:flex-start;padding-bottom:9px;border-bottom:1.5px solid var(--navy)}}.wm{{width:205px}}.wm svg{{width:100%;height:auto;display:block}}.sender{{text-align:right;font-family:var(--mono);font-size:7.7px;letter-spacing:.08em;color:var(--ink-dim);line-height:1.7}}.sender .name{{font-family:var(--display);font-size:15px;letter-spacing:.06em;color:var(--navy)}}.sender .role{{color:var(--cyan-ink);text-transform:uppercase;letter-spacing:.15em}}.sender a{{color:var(--ink-dim);text-decoration:none}}
.meta{{display:flex;justify-content:space-between;font-family:var(--mono);font-size:8px;letter-spacing:.1em;color:var(--ink-xdim);text-transform:uppercase;margin:11px 0 13px}}.meta .channel{{color:var(--cyan-ink)}}.to{{font-size:10.8px;line-height:1.42}}.to .label{{font-family:var(--mono);font-size:7.2px;letter-spacing:.2em;text-transform:uppercase;color:var(--ink-xdim);display:block;margin-bottom:3px}}.email{{font-family:var(--mono);font-size:7.5px;color:var(--cyan-ink)}}
.compact{{font-size:9.15px;line-height:1.31}}.compact .letter p{{margin-bottom:5px}}.compact .letter li{{margin-bottom:3px}}.compact .letter h2{{margin-top:10px}}.ultracompact{{font-size:8.55px;line-height:1.24}}.ultracompact .letter p{{margin-bottom:4px}}.ultracompact .letter li{{margin-bottom:2px}}.ultracompact .letter h2{{margin:8px 0 4px}}.ultracompact .re{{margin:9px 0 9px;padding:7px 11px}}
.re{{margin:13px 0 14px;padding:9px 13px;background:var(--surface);border-left:3px solid var(--gold)}}.re .label{{font-family:var(--mono);font-size:7.2px;letter-spacing:.2em;text-transform:uppercase;color:var(--gold-ink)}}.re .subject{{font-weight:600;font-size:10.5px;color:var(--navy);margin-top:3px;line-height:1.3}}.letter p{{margin:0 0 7px}}.letter h2{{font-family:var(--display);font-weight:400;font-size:13px;letter-spacing:.04em;color:var(--navy);text-transform:uppercase;margin:15px 0 6px;padding-bottom:3px;border-bottom:.75px solid rgba(5,10,26,.14);break-after:avoid}}.letter ol,.letter ul{{margin:2px 0 8px 20px}}.letter li{{margin-bottom:5px;padding-left:2px;break-inside:avoid}}.letter strong{{font-weight:700}}.signoff{{margin-top:10px;break-inside:avoid;page-break-inside:avoid}}.wetsig{{display:block;height:38px;width:auto;margin:3px 0 -5px 2px}}.sig-name{{font-family:var(--display);font-size:17px;letter-spacing:.05em;color:var(--navy);margin-top:5px}}.sig-meta{{font-family:var(--mono);font-size:7.8px;letter-spacing:.08em;color:var(--ink-dim);line-height:1.6}}.engine{{display:flex;align-items:center;gap:8px;font-family:var(--mono);font-size:7px;letter-spacing:.14em;text-transform:uppercase;color:var(--navy);margin-top:12px}}.engine::before{{content:"";flex:1;height:1px;background:linear-gradient(90deg,var(--cyan),transparent)}}.engine .dot{{width:5px;height:5px;border-radius:50%;background:var(--cyan)}}.engine .gold{{color:var(--gold-ink)}}
</style></head><body class="{body_class}">
<header><div class="wm">{WORDMARK}</div><div class="sender"><div class="name">ABRAHAM ROSENWALD</div><div class="role">SELF-REPRESENTED PARTY</div><div>{ADDRESS}</div><div>{CITY}</div><div><a href="mailto:{EMAIL}">{EMAIL}</a> &middot; {PHONE}</div><div>Appearing Pro Se</div></div></header>
<div class="meta"><span>{DATE}</span><span class="channel">{CHANNEL}</span></div><div class="to"><span class="label">To</span>{rec}<br/><strong>{html.escape(L['firm'])}</strong><br/>{html.escape(L['street'])}<br/>{html.escape(L['city'])}{email_line}</div>
<div class="re"><span class="label">Re</span><div class="subject">{html.escape(L['subject'])}</div></div><section class="letter"><p>Dear {html.escape(L['salutation'].replace('Dear ',''))},</p>{body_html}</section>
<div class="signoff"><div>Respectfully,</div>{sig_html}<div class="sig-name">ABRAHAM ROSENWALD</div><div class="sig-meta">SELF-REPRESENTED PARTY<br/>Appearing Pro Se<br/>{EMAIL} &middot; {PHONE}</div><div class="engine"><span class="dot"></span>Drafted with the <span class="gold">ELARIA Document Engine</span> · AVOWAL.AI</div></div></body></html>'''

index=[]
for L in letters:
    md, count = body_markdown(L)
    md_path=MDDIR/f"{L['id']}.md"; md_path.write_text(md)
    body_html=to_html(md)
    doc=render_html(L,body_html,count)
    hp=HTMLDIR/f"{L['id']}.html"; hp.write_text(doc)
    pp=PDFDIR/f"{L['id']}.pdf"
    cp=subprocess.run([CHROME,'--headless','--disable-gpu','--no-pdf-header-footer',f'--print-to-pdf={pp}',f'file://{hp}'],capture_output=True,text=True)
    if cp.returncode != 0 or not pp.exists(): raise RuntimeError(f"Chrome failed {L['id']}: {cp.stderr}")
    # Chrome does not reliably paint margin-box backgrounds to the physical sheet edge.
    # Draw the AVOWAL cyan/gold spine directly into every PDF page at x=0 so it is true full bleed.
    rendered = fitz.open(str(pp))
    for page in rendered:
        h = page.rect.height; w = page.rect.width
        page.draw_rect(fitz.Rect(0, 0, 5.5, h * .62), color=None, fill=(0, 212/255, 1), overlay=True)
        page.draw_rect(fitz.Rect(0, h * .62, 5.5, h), color=None, fill=(240/255, 180/255, 41/255), overlay=True)
        # Disclaimer is drawn directly into the reserved 1.02in bottom margin band.
        # Content never flows into the page margin, so this footer can never collide with body text.
        dl_left, dl_right = 62.0, w - 52.0
        page.draw_line(fitz.Point(dl_left, h - 66), fitz.Point(dl_right, h - 66),
                       color=(0.02, 0.04, 0.10), width=0.6)
        page.insert_textbox(fitz.Rect(dl_left, h - 61, dl_right, h - 31), DISCLAIMER,
                            fontfile=DISC_FONT, fontname='dmmono', fontsize=5.7,
                            color=(0.32, 0.38, 0.48), lineheight=1.3)
        page.insert_textbox(fitz.Rect(dl_left, h - 30, dl_right, h - 20), 'avowal.ai',
                            fontfile=DISC_FONT, fontname='dmmono', fontsize=5.7,
                            color=(0.0, 0.537, 0.658))
    tmp_pdf = pp.with_suffix('.spine.pdf')
    rendered.save(str(tmp_pdf), garbage=4, deflate=True)
    rendered.close()
    tmp_pdf.replace(pp)
    dp=DOCXDIR/f"{L['id']}.docx"
    subprocess.run([PANDOC,str(md_path),'-o',str(dp),'--metadata',f"title={L['subject']}"],check=True)
    index.append({'id':L['id'],'firm':L['firm'],'recipient':L['recipient'].replace('\n','; '),'address':f"{L['street']}, {L['city']}",'email':L.get('email',''),'requests':count,'pdf':str(pp),'docx':str(dp)})

(OUT/'letter_index.json').write_text(json.dumps(index,indent=2))
# Markdown index and mailing log.
rows=['# AVOWAL entity request-letter index','',f'Date: {DATE}','',f'{len(index)} entity-specific letters generated. Every private-party letter is a voluntary inquiry; agency letters invoke or request applicable public-record procedures.','', '| # | Entity | Recipient | Requests | PDF |','|---:|---|---|---:|---|']
for i,x in enumerate(index,1): rows.append(f"| {i} | {x['firm']} | {x['recipient']} | {x['requests']} | `{Path(x['pdf']).name}` |")
rows += ['','## Mailing log','','| Entity | Method | Tracking / confirmation | Sent | Delivered | Response due | Status |','|---|---|---|---|---|---|---|']
for x in index: rows.append(f"| {x['firm']} | Email + certified mail | | | | | Draft |")
(OUT/'INDEX_AND_MAILING_LOG.md').write_text('\n'.join(rows)+'\n')
subprocess.run([PANDOC,str(OUT/'INDEX_AND_MAILING_LOG.md'),'-o',str(OUT/'INDEX_AND_MAILING_LOG.docx')],check=True)
print(json.dumps({'count':len(index),'out':str(OUT),'letters':[{'id':x['id'],'requests':x['requests']} for x in index]},indent=2))
