"""Versioned bilingual private PDF reports; deterministic chart facts only."""
from datetime import datetime, timezone
from io import BytesIO
from itertools import groupby
from pathlib import Path
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.colors import HexColor, white

FONT, NEFONT = 'KundaliNoto', 'KundaliNotoDevanagari'
FONTDIR = Path(__file__).parent / 'fonts'
SIGNS = ['Aries','Taurus','Gemini','Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricorn','Aquarius','Pisces']
NE_SIGNS = ['मेष','वृष','मिथुन','कर्कट','सिंह','कन्या','तुला','वृश्चिक','धनु','मकर','कुम्भ','मीन']
PLANETS = ['Sun','Moon','Mars','Mercury','Jupiter','Venus','Saturn','Rahu','Ketu']
NE_PLANETS = ['सूर्य','चन्द्र','मंगल','बुध','बृहस्पति','शुक्र','शनि','राहु','केतु']
NAKS = ['Ashwini','Bharani','Krittika','Rohini','Mrigashira','Ardra','Punarvasu','Pushya','Ashlesha','Magha','Purva Phalguni','Uttara Phalguni','Hasta','Chitra','Swati','Vishakha','Anuradha','Jyeshtha','Mula','Purva Ashadha','Uttara Ashadha','Shravana','Dhanishta','Shatabhisha','Purva Bhadrapada','Uttara Bhadrapada','Revati']
NE_NAKS = ['अश्विनी','भरणी','कृत्तिका','रोहिणी','मृगशिरा','आर्द्रा','पुनर्वसु','पुष्य','अश्लेषा','मघा','पूर्वफाल्गुनी','उत्तरफाल्गुनी','हस्त','चित्रा','स्वाती','विशाखा','अनुराधा','ज्येष्ठा','मूल','पूर्वाषाढा','उत्तराषाढा','श्रवण','धनिष्ठा','शतभिषा','पूर्वभाद्रपद','उत्तरभाद्रपद','रेवती']
DISCLAIMER = 'Traditional astrology is offered for reflection and entertainment. It cannot scientifically establish past events or reliably predict future outcomes. Do not use this report for medical, legal, financial or other consequential decisions.'
NEPALI = 'यो कुण्डली परम्परागत ज्योतिषमा आधारित आत्मचिन्तनका लागि हो। भविष्यको निश्चित वा वैज्ञानिक प्रमाण होइन।'
INDIGO, GOLD, GRAY = HexColor('#27234b'), HexColor('#ad7f31'), HexColor('#56566b')
TRANSLATIONS = {
 'JYOTISH / JANMA KUNDALI':'ज्योतिष / जन्म कुण्डली',
 'Birth details and chart overview':'जन्म विवरण र कुण्डली',
 'Calculated placements / Traditional interpretations / Explicit assumptions':'गणना गरिएका ग्रहस्थिति / परम्परागत व्याख्या / स्पष्ट मान्यता',
 'Profile':'व्यक्तिको नाम','Birth date / local time':'जन्म मिति / स्थानीय समय','Birthplace':'जन्मस्थान',
 'Coordinates / IANA time zone':'अक्षांश–देशान्तर / IANA समय क्षेत्र','UTC instant / offset seconds':'UTC समय / समय अन्तर (सेकेन्ड)',
 'Time accuracy':'जन्म समयको शुद्धता','Unknown':'अज्ञात','Not supplied':'प्रदान गरिएको छैन','Not available':'उपलब्ध छैन',
 'exact':'यकिन','approximate':'अनुमानित','unknown':'अज्ञात','Assumption: ':'मान्यता: ',
 'D1 and D9 charts':'राशि र नवांश कुण्डली','Fixed-sign South Indian diagrams / Sidereal zodiac':'स्थिर राशि भएको दक्षिण भारतीय शैली / निरयण राशि चक्र',
 'D1 / Rashi':'D1 / राशि','D9 / Navamsa':'D9 / नवांश','Fixed signs':'स्थिर राशि','Fixed houses':'स्थिर भाव',
 'Asc = Ascendant; planet labels use first three letters. House system: whole-sign.':'ल = लग्न; ग्रहको छोटो नाम प्रयोग गरिएको छ। भाव पद्धति: पूर्ण राशि।',
 'Planetary positions and planetary periods':'ग्रहस्थिति र ग्रहदशा','Sidereal zodiac / The chart engine provides the following facts':'निरयण राशि चक्र / गणना इन्जिनबाट प्राप्त तथ्य',
 'Engine: ':'गणना इन्जिन: ','Ephemeris: ':'खगोलीय पद्धति: ','Ayanamsa: ':'अयनांश: ',' / Nodes: ':' / राहु–केतु: ',' / Houses: ':' / भाव: ',
 'lahiri':'लाहिरी','raman':'रमण','krishnamurti':'कृष्णमूर्ति','mean':'मध्यम','true':'वास्तविक','whole-sign':'पूर्ण राशि',
 'Body':'ग्रह','Sign / degree':'राशि / अंश','Nakshatra':'नक्षत्र','Pada':'पाद','House':'भाव','Motion':'गति','Retrograde':'वक्री','Direct':'मार्गी',
 'Vimshottari Mahadasha timeline':'विंशोत्तरी महादशा समयरेखा','Interpretation and limitations':'परम्परागत व्याख्या र सीमाहरू',
 'Use traditional symbolism as a prompt for reflection':'परम्परागत प्रतीकलाई आत्मचिन्तनको आधार मान्नुहोस्',
 'Important limitations':'महत्वपूर्ण सीमाहरू','Private report / Generated ':'निजी प्रतिवेदन / तयार गरिएको समय ', 'Page ':'पृष्ठ ',
 'Full Antardasha appendix':'अन्तर्दशाको विस्तृत परिशिष्ट','Mahadasha / Antardasha / Start / End':'महादशा / अन्तर्दशा / सुरु / अन्त्य',
 'Mahadasha':'महादशा','Antardasha':'अन्तर्दशा','Start':'सुरु','End':'अन्त्य',
 'Calendar dates are Gregorian. Boundaries are UTC. Earlier periods may begin before birth.':'मितिहरू इस्वी संवत् अनुसार छन्। समयसीमा UTC हो। पहिलो दशा जन्मभन्दा अघि सुरु भएको हुन सक्छ।',
 'Calculation provenance':'गणनाको स्रोत विवरण','Report rules: report-v2 / Chart schema: ':'प्रतिवेदन नियम: report-v2 / कुण्डली संरचना: ',
 'Instant Panchanga':'त्यस क्षणको पञ्चाङ्ग','Tithi number: ':'तिथि क्रमांक: ',' / Yoga number: ':' / योग क्रमांक: ',
 'Only instant tithi and yoga are shown; this is not a complete sunrise-based Panchanga.':'क्षणगत तिथि र योग मात्र देखाइएको छ; यो सूर्योदयमा आधारित पूर्ण पञ्चाङ्ग होइन।',
}
TRANSLATIONS.update(dict(zip(SIGNS,NE_SIGNS)))
TRANSLATIONS.update(dict(zip(PLANETS,NE_PLANETS)))
TRANSLATIONS.update(dict(zip(NAKS,NE_NAKS)))


def _font_runs(text):
    # Keep spaces and punctuation with adjacent script so Unicode extraction
    # retains natural words while mixed scientific identifiers remain legible.
    previous=False
    current=''
    for ch in str(text):
        script=True if '\u0900' <= ch <= '\u097f' else (False if ch.isalnum() else previous)
        if current and script != previous:
            yield NEFONT if previous else FONT,current
            current=''
        current+=ch
        previous=script
    if current:
        yield NEFONT if previous else FONT,current


def build_report(profile: dict, chart: dict) -> bytes:
    if not isinstance(profile, dict) or not isinstance(chart, dict):
        raise ValueError('profile and chart must be objects')
    if 'planets' not in chart or not isinstance(chart['planets'], dict):
        raise ValueError('chart.planets must be an object from the calculation engine')
    if len(chart['planets']) > 12:
        raise ValueError('Unexpected number of chart bodies')
    if FONT not in pdfmetrics.getRegisteredFontNames():
        pdfmetrics.registerFont(TTFont(FONT, str(FONTDIR / 'NotoSans-Regular.ttf')))
        pdfmetrics.registerFont(TTFont(NEFONT, str(FONTDIR / 'NotoSansDevanagari-Regular.ttf')))
    ne = profile.get('language') == 'ne'
    chart_style = profile.get('chart_style','south')
    if chart_style not in ('north','south'):
        raise ValueError('chart_style must be north or south')
    t = lambda s: TRANSLATIONS.get(str(s),str(s)) if ne else str(s)
    stream = BytesIO()
    c = canvas.Canvas(stream, pagesize=(595.28, 841.89), pageCompression=1)
    c.setTitle(t('JYOTISH / JANMA KUNDALI'))
    c.setAuthor('Jyotish')
    page = 0
    generated = datetime.now(timezone.utc)

    def width(text, size):
        return sum(pdfmetrics.stringWidth(run,font,size) for font,run in _font_runs(text))

    def txt(x, y, text, size=10, color=INDIGO):
        c.setFillColor(color)
        for font,run in _font_runs(str(text)[:2000]):
            c.setFont(font,size)
            c.drawString(x,y,run,shaping=font == NEFONT)
            x += pdfmetrics.stringWidth(run,font,size)

    def wrap(text, y, size=10, available=499, leading=17):
        line=''
        words=[]
        for word in str(text).split():
            part=''
            for ch in word:
                if part and width(part+ch,size)>available:
                    words.append(part); part=ch
                else:part+=ch
            if part:words.append(part)
        for word in words:
            candidate = (line+' '+word).strip()
            if line and width(candidate,size)>available:
                txt(48,y,line,size); y-=leading; line=word
            else:
                line=candidate
        if line:
            txt(48,y,line,size); y-=leading
        return y

    def new_page(title, subtitle):
        nonlocal page
        if page:
            c.showPage()
        page += 1
        c.setFillColor(INDIGO); c.rect(0,750,596,92,fill=1,stroke=0)
        txt(48,800,t('JYOTISH / JANMA KUNDALI'),19,white)
        txt(48,774,t(title),13,HexColor('#efcf8b'))
        txt(48,722,t(subtitle),10,GRAY)
        c.setStrokeColor(GOLD); c.line(48,706,547,706)
        txt(48,28,t('Private report / Generated ')+generated.strftime('%Y-%m-%d %H:%M UTC'),8,GRAY)
        txt(503,28,t('Page ')+str(page),8,GRAY)
        return 681

    def chart_box(x,y,positions,label,ascendant):
        size,cell = 234,58.5
        c.setStrokeColor(GOLD)
        abbreviations = dict(zip(PLANETS,['सू','चं','मं','बु','गु','शु','श','रा','के']))
        if chart_style == 'north' and ascendant is not None:
            c.rect(x,y,size,size,stroke=1,fill=0)
            c.line(x,y,x+size,y+size); c.line(x,y+size,x+size,y)
            p=c.beginPath(); p.moveTo(x+size/2,y+size);p.lineTo(x+size,y+size/2);p.lineTo(x+size/2,y);p.lineTo(x,y+size/2);p.close();c.drawPath(p)
            centers=[(150,73),(75,38),(38,76),(73,150),(38,225),(75,263),(150,226),(225,263),(263,225),(226,150),(263,76),(225,38)]
            for house,(px,py) in enumerate(centers):
                sign=(house+ascendant)%12
                xx,yy=x+px/300*size,y+(300-py)/300*size
                txt(xx-5,yy+10,str(sign+1),7,GRAY)
                names=[abbreviations.get(k,k[:3]) if ne else k[:3] for k,v in positions.items() if v==sign]
                if house==0:names.insert(0,'ल' if ne else 'Asc')
                for idx in range(0,len(names),3):
                    line=' '.join(names[idx:idx+3]);txt(xx-width(line,6.5)/2,yy-idx/3*9,line,6.5)
            txt(x,y-17,t(label)+' / '+t('Fixed houses'),9)
        else:
            cells=[(1,0),(2,0),(3,0),(3,1),(3,2),(3,3),(2,3),(1,3),(0,3),(0,2),(0,1),(0,0)]
            for sign,(col,row) in enumerate(cells):
                left,bottom=x+col*cell,y+(3-row)*cell
                c.rect(left,bottom,cell,cell,stroke=1,fill=0)
                txt(left+4,bottom+cell-13,NE_SIGNS[sign] if ne else SIGNS[sign][:3],8,GRAY)
                names=[abbreviations.get(k,k[:3]) if ne else k[:3] for k,v in positions.items() if v==sign]
                if ascendant==sign:names.insert(0,'ल' if ne else 'Asc')
                for idx,name in enumerate(names):txt(left+4+(idx%2)*27,bottom+cell-24-(idx//2)*8,name,7)
            txt(x+cell+10,y+size/2+8,t(label),11)
            txt(x+cell+10,y+size/2-13,t('Fixed signs'),8,GRAY)

    y=new_page('Birth details and chart overview','Calculated placements / Traditional interpretations / Explicit assumptions')
    fields=[('Profile',profile.get('name','Birth profile')),('Birth date / local time',str(profile.get('birth_date',''))+' / '+str(profile.get('birth_time') or t('Unknown'))),('Birthplace',profile.get('place',t('Not supplied'))),('Coordinates / IANA time zone',str(profile.get('latitude',''))+', '+str(profile.get('longitude',''))+' / '+str(profile.get('timezone',''))),('UTC instant / offset seconds',str(chart.get('utc',t('Not available')))+' / '+str(chart.get('utc_offset_seconds',t('Not available')))),('Time accuracy',t(chart.get('accuracy',profile.get('accuracy','Not specified'))))]
    for label,value in fields:
        txt(48,y,t(label),9,GRAY);y=wrap(str(value)[:250],y-17,10,leading=15)-12
    warnings=chart.get('warnings',[])[:4]
    if ne:
        if chart.get('accuracy')=='unknown':warnings=['जन्म समय अज्ञात छ। लग्न, भाव, नवांश र दशा अनुमान गरी बनाइएको छैन। समय उपलब्ध भएपछि कुण्डली बनाउनुहोस्।']
        elif chart.get('accuracy')=='approximate':warnings=['अनुमानित जन्म समयका कारण लग्न, भाव, नवांश र दशाको समयसीमा फरक हुन सक्छ। गणनामा प्रदान गरिएको समय नै प्रयोग गरिएको छ।']
    for warning in warnings:y=wrap(t('Assumption: ')+str(warning),y,9,leading=14)-6
    if chart['planets']:
        if y<380:y=new_page('D1 and D9 charts','Fixed-sign South Indian diagrams / Sidereal zodiac')
        asc=chart.get('ascendant') or {}
        chart_box(48,115,chart.get('d1',{}),'D1 / Rashi',asc.get('sign_index'))
        chart_box(313,115,chart.get('d9',{}),'D9 / Navamsa',asc.get('navamsa_sign_index'))
        txt(48,80,t('Asc = Ascendant; planet labels use first three letters. House system: whole-sign.'),8,GRAY)
    else:
        y=wrap('जन्म समय अज्ञात छ। कुनै कुण्डली, लग्न वा दशा अनुमान गरी बनाइएको छैन।' if ne else 'Birth time is unknown. No chart, Ascendant or dasha has been invented. Supply a birth time to generate these elements.',y-20)
    wrap(NEPALI,58,8,leading=13)

    y=new_page('Planetary positions and planetary periods','Sidereal zodiac / The chart engine provides the following facts')
    settings=chart.get('settings',{})
    y=wrap(t('Engine: ')+str(chart.get('engine',t('Not available'))),y,9)-3
    y=wrap(t('Ephemeris: ')+str(chart.get('ephemeris',t('Not available'))),y,9)-3
    y=wrap(t('Ayanamsa: ')+t(settings.get('ayanamsa',''))+t(' / Nodes: ')+t(settings.get('node',''))+t(' / Houses: ')+t(settings.get('houses','')),y,9)-17
    cols=[48,116,215,292,353,454]
    for x,label in zip(cols,['Body','Sign / degree','Nakshatra','Pada','House','Motion']):txt(x,y,t(label),9,GOLD)
    y-=23
    for name,p in chart['planets'].items():
        vals=[t(name),t(p.get('sign',''))+' '+f"{float(p.get('degree',0)):.3f}",t(p.get('nakshatra','')),p.get('pada',''),p.get('house',''),t('Retrograde') if p.get('retrograde') else t('Direct')]
        for x,val in zip(cols,vals):txt(x,y,val,8)
        y-=23
    y-=16;txt(48,y,t('Vimshottari Mahadasha timeline'),13);y-=22
    convention=('दशा वर्ष: '+str(settings.get('dasha_year_days',365.25))+' दिन। समयसीमा प्रदान गरिएको जन्म समयमा निर्भर हुन्छ।' if ne else 'Period convention: '+str(settings.get('dasha_year_days',365.25))+' days per year. Boundaries depend on the supplied birth time.')
    y=wrap(convention,y,9)-6
    for d in chart.get('dashas',[])[:10]:
        txt(48,y,t(d.get('lord','')),9);txt(135,y,str(d.get('start',''))[:10]+'  —  '+str(d.get('end',''))[:10],9);y-=19

    y=new_page('Interpretation and limitations','Use traditional symbolism as a prompt for reflection')
    moon=chart['planets'].get('Moon')
    if moon:
        s=t(moon.get('sign',''));nak=t(moon.get('nakshatra',''));pada=str(moon.get('pada',''))
        y=wrap(('चन्द्रस्थिति: '+s+'; '+nak+' नक्षत्र; पाद '+pada+'।') if ne else ('Moon placement: '+s+'; '+nak+' Nakshatra; Pada '+pada+'.'),y,11)-12
        text='परम्परागत ज्योतिषमा चन्द्रलाई भावना, बानी र व्यक्तिगत अनुभवसँग जोडिन्छ। आफ्नो भावनात्मक प्रतिक्रिया तथा सहयोग आवश्यक पर्ने अवस्थाबारे विचार गर्नुहोस्। यसले व्यक्तित्व वा नबताइएका विगतका घटना प्रमाणित गर्दैन।' if ne else 'Traditional Jyotish associates the Moon with emotional habits and subjective experience. Reflect on your emotional responses and the situations in which support helps you. This symbolism does not establish your personality or undisclosed past events.'
        y=wrap(text,y)-15
    asc=chart.get('ascendant')
    if asc:
        text=('लग्न: '+t(asc.get('sign',''))+'। परम्परागत व्याख्यामा लग्नलाई जीवनका विषय हेर्ने आधार मानिन्छ। जन्म समयको शुद्धता यसको मुख्य सीमा हो।') if ne else ('Ascendant: '+str(asc.get('sign',''))+'. Traditional readings use the Ascendant to organize life themes. Its reliability depends strongly on the recorded birth time.')
        y=wrap(text,y)-15
    # Versioned, chart-linked reflection templates. These describe domain
    # symbolism and the actual whole-sign house; they do not infer life events.
    house_topics={1:('identity and personal habits','पहिचान र व्यक्तिगत बानी'),2:('resources and speech','स्रोतसाधन र बोली'),3:('skills and communication','सीप र संवाद'),4:('home and personal foundations','घर र व्यक्तिगत आधार'),5:('creativity and learning','सिर्जनशीलता र सिकाइ'),6:('routine and service','दैनिक अभ्यास र सेवा'),7:('partnership and cooperation','साझेदारी र सहकार्य'),8:('shared resources and change','साझा स्रोत र परिवर्तन'),9:('beliefs and higher learning','विश्वास र उच्च शिक्षा'),10:('work and public responsibility','काम र सार्वजनिक जिम्मेवारी'),11:('community and long-term goals','समुदाय र दीर्घकालीन लक्ष्य'),12:('rest and private reflection','विश्राम र निजी आत्मचिन्तन')}
    themes={'Mercury':('communication and learning','संवाद र सिकाइ'),'Jupiter':('knowledge and guidance','ज्ञान र मार्गदर्शन'),'Saturn':('discipline and responsibility','अनुशासन र जिम्मेवारी')}
    for body,(theme,ne_theme) in themes.items():
        placement=chart['planets'].get(body)
        if not placement:continue
        house=placement.get('house')
        topic,ne_topic=house_topics.get(house,('life themes','जीवनका विषय'))
        text=(t(body)+' '+t(placement.get('sign',''))+' राशिमा, भाव '+str(house)+'। report-v2 अनुसार '+ne_theme+' लाई '+ne_topic+' सँग जोडेर आफ्नो अनुभवबारे विचार गर्नुहोस्। यसले घटना वा नतिजा निश्चित गर्दैन।') if ne else (body+' in '+str(placement.get('sign',''))+', house '+str(house)+'. Reflection rule report-v2: consider '+theme+' in relation to '+topic+'. This invites reflection on your own experience; it does not predict events.')
        y=wrap(text,y,9,leading=15)-10
    panchanga=chart.get('panchanga',{})
    if panchanga:
        txt(48,y,t('Instant Panchanga'),12);y-=21
        y=wrap(t('Tithi number: ')+str(panchanga.get('tithi',''))+t(' / Yoga number: ')+str(panchanga.get('yoga','')),y,9)-4
        note=('माथिका मान क्षणगत हुन्; सूर्योदयमा आधारित पञ्चाङ्ग स्रोत विवरणमा दिइएको छ।' if ne else 'Values above are instant-based. Sunrise-based Panchanga appears in the calculation details.') if panchanga.get('sunrise_day') else t('Only instant tithi and yoga are shown; this is not a complete sunrise-based Panchanga.')
        y=wrap(note,y,9)-12
    txt(48,y,t('Important limitations'),13);y-=25
    disclaimer='परम्परागत ज्योतिष आत्मचिन्तन र मनोरञ्जनका लागि प्रस्तुत गरिएको हो। यसले विगतका घटना वैज्ञानिक रूपमा प्रमाणित गर्न वा भविष्य विश्वसनीय रूपमा बताउन सक्दैन। चिकित्सा, कानुनी, आर्थिक वा अन्य महत्वपूर्ण निर्णयका लागि यस प्रतिवेदनमा निर्भर नहुनुहोस्।' if ne else DISCLAIMER
    y=wrap(disclaimer,y,10)-12
    text='नवांश, पूर्ण राशि भाव र दशाको समयसीमा जन्म समयअनुसार फरक हुन सक्छ। मृत्युको मिति, रोग निदान, निश्चित नतिजा वा महँगा उपचार सुझाइएको छैन।' if ne else 'D9, whole-sign houses and dasha boundaries depend on the supplied birth time. No death dates, medical diagnoses, guaranteed outcomes or costly remedies are provided.'
    y=wrap(text,y,10)-12
    text='प्रतिवेदनका व्याख्या report-v2 का परम्परागत आत्मचिन्तन नियम हुन्; AI भविष्यवाणी होइनन्। सुरक्षित च्याट वार्तालाप यस PDF मा समावेश छैन।' if ne else 'Narrative content uses versioned traditional reflection rules (report-v2), not AI predictions. Saved chat conversations are not included in this PDF.'
    y=wrap(text,y,9)-10
    y=wrap(t('Report rules: report-v2 / Chart schema: ')+str(chart.get('schema_version','1.0')),y,8)

    provenance=chart.get('provenance',{})
    patterns=chart.get('patterns',{})
    uncertainty=chart.get('uncertainty',{})
    sunrise=panchanga.get('sunrise_day') or {}
    if provenance or patterns or uncertainty or sunrise:
        title='पञ्चाङ्ग, परम्परागत नियम र स्रोत' if ne else 'Panchanga, traditional rules and provenance'
        subtitle='नियमका सीमा र गणनाको पुनरुत्पादन' if ne else 'Rule limitations and reproducible calculation details'
        y=new_page(title,subtitle)
        def detail(text):
            nonlocal y
            if y<150:y=new_page(title,subtitle)
            y=wrap(text,y,9,leading=15)-8
        if sunrise:
            karanas={'Bava':'बव','Balava':'बालव','Kaulava':'कौलव','Taitila':'तैतिल','Garaja':'गर','Vanija':'वणिज','Vishti':'विष्टि','Kimstughna':'किंस्तुघ्न','Shakuni':'शकुनि','Chatushpada':'चतुष्पद','Naga':'नाग'}
            detail(('स्थानीय सूर्योदय मिति: ' if ne else 'Local sunrise date: ')+str(sunrise.get('local_date','')))
            detail(('सूर्योदयको स्थानीय समय: ' if ne else 'Sunrise local time: ')+str(sunrise.get('sunrise_local','')))
            weekdays={'Monday':'सोमबार','Tuesday':'मंगलबार','Wednesday':'बुधबार','Thursday':'बिहीबार','Friday':'शुक्रबार','Saturday':'शनिबार','Sunday':'आइतबार'}
            vara=sunrise.get('vara','')
            detail(('वार: '+weekdays.get(vara,vara)+' / तिथि: '+str(sunrise.get('tithi',''))+' / नक्षत्र: '+t(sunrise.get('nakshatra',''))+' / योग: '+str(sunrise.get('yoga',''))+' / करण: '+karanas.get(sunrise.get('karana',''),str(sunrise.get('karana','')))) if ne else ('Vara: '+vara+' / Tithi: '+str(sunrise.get('tithi',''))+' / Nakshatra: '+str(sunrise.get('nakshatra',''))+' / Yoga: '+str(sunrise.get('yoga',''))+' / Karana: '+str(sunrise.get('karana',''))))
            for limb,boundary in sunrise.get('ends_utc',{}).items():
                labels={'tithi':'तिथि','nakshatra':'नक्षत्र','yoga':'योग','karana':'करण'}
                detail((labels.get(limb,limb)+' समाप्त हुने UTC समय: ' if ne else limb.title()+' ends at UTC: ')+str(boundary))
            detail('सीमा: सूर्योदयमा आधारित पाँच अङ्ग प्रयोग गरिएका छन्। भूभाग, उचाइ र स्थानीय वायुमण्डलीय सुधार समावेश छैनन्।' if ne else 'Convention: five limbs at the most recent local sunrise; terrain, elevation and local atmospheric corrections are not modeled.')
        elif panchanga:
            detail('सम्बन्धित स्थान वा मितिमा सूर्योदय उपलब्ध नभएकाले क्षणगत पञ्चाङ्ग मात्र देखाइएको छ।' if ne else 'Sunrise-based Panchanga is unavailable for the relevant place/date; only instant limbs are shown.')
        if uncertainty:
            detail(('अनुमानित समयको परीक्षण: ±'+str(uncertainty.get('plus_minus_minutes',''))+' मिनेट। यो नमुना परीक्षण हो; पूर्ण समयसीमाको प्रमाण वा सम्भावना होइन।') if ne else ('Approximate-time sensitivity: ±'+str(uncertainty.get('plus_minus_minutes',''))+' minutes. This is sampled sensitivity, not exhaustive interval proof or probability.'))
            detail(('नमुनामा देखिएका लग्न: ' if ne else 'Sampled Ascendants: ')+', '.join(t(x) for x in uncertainty.get('ascendant_signs',[]))+(' / नवांश लग्न: ' if ne else ' / D9 Ascendants: ')+', '.join(t(x) for x in uncertainty.get('ascendant_d9_signs',[])))
        ne_rules={
            'budha-aditya-conjunction':('बुध–आदित्य स्थिति','सूर्य र बुध एउटै निरयण राशिमा छन् कि छैनन्। अस्त, बल र योगभङ्गका अन्य रूप जाँचिएको छैन।'),
            'gaja-kesari-kendra':('गजकेसरी स्थिति','चन्द्रबाट गनिएको पहिलो, चौथो, सातौँ वा दशौँ पूर्ण राशिमा बृहस्पति छन् कि छैनन्। बल, दृष्टि र योगभङ्ग जाँचिएको छैन।'),
            'chandra-mangala-conjunction':('चन्द्र–मंगल स्थिति','चन्द्र र मंगल एउटै निरयण राशिमा छन् कि छैनन्। पारस्परिक दृष्टिका अन्य रूप समावेश छैनन्।'),
            'manglik-lagna-selected-houses':('मंगलको भाव स्थिति','लग्नबाट १, २, ४, ७, ८ वा १२ भावमा मंगल छन् कि छैनन्। परम्परामा मतभेद छन्; योगभङ्ग तथा चन्द्र वा शुक्रबाट गणना जाँचिएको छैन।'),
        }
        if patterns:
            detail('निम्न ज्यामितीय स्थिति परम्परागत नियम मात्र हुन्। सम्बन्धको गुणस्तर, हानि वा निश्चित नतिजाबारे निर्णय गर्न मिल्दैन।' if ne else 'The following geometric conditions are traditional rules only. They do not establish relationship quality, harm or guaranteed outcomes.')
        for rule in patterns.get('rules',[])[:8]:
            label,definition=ne_rules.get(rule.get('id'),(rule.get('name',''),rule.get('definition',''))) if ne else (rule.get('name',''),rule.get('definition',''))
            status=('सर्त मिलेको' if rule.get('present') else 'सर्त नमिलेको') if ne else ('Condition present' if rule.get('present') else 'Condition absent')
            detail(label+' / '+status+' / v'+str(rule.get('version',''))+': '+definition)
        if provenance:
            detail(('समय क्षेत्र तथ्याङ्क: ' if ne else 'Time-zone data: ')+str(provenance.get('tzdata','')))
            detail(('सफ्टवेयर: Python ' if ne else 'Software: Python ')+str(provenance.get('python',''))+' / pyswisseph '+str(provenance.get('pyswisseph',''))+' / Swiss '+str(provenance.get('swisseph','')))
            detail(('गणना स्रोतको SHA-256: ' if ne else 'Calculator source SHA-256: ')+str(provenance.get('calculator_source_sha256','')))
            detail('समयसम्बन्धी सीमा: UTC लाई UT को रूपमा प्रयोग गरिएको छ; सन् १९७२ अघिको UTC/UT1 अन्तर र लीप सेकेन्ड अलग रूपमा मोडल गरिएको छैन।' if ne else str(provenance.get('time_basis','')))

    # Full Antardasha appendix, bounded at 10 x 9 rows and paginated explicitly.
    rows=[(d.get('lord',''),a) for d in chart.get('dashas',[])[:10] for a in d.get('antardashas',[])[:9]]
    if rows:
        def appendix_page():
            yy=new_page('Full Antardasha appendix','Mahadasha / Antardasha / Start / End')
            yy=wrap(t('Calendar dates are Gregorian. Boundaries are UTC. Earlier periods may begin before birth.'),yy,9)-8
            for xx,label in zip([48,155,265,400],['Mahadasha','Antardasha','Start','End']):txt(xx,yy,t(label),9,GOLD)
            return yy-25
        y=appendix_page()
        for lord,a in rows:
            if y<75:y=appendix_page()
            for x,val in zip([48,155,265,400],[t(lord),t(a.get('lord','')),str(a.get('start',''))[:10],str(a.get('end',''))[:10]]):txt(x,y,val,9)
            y-=18
    c.save()
    return stream.getvalue()
