from io import BytesIO
import os
import pytest
from fastapi.testclient import TestClient
from pypdf import PdfReader
from app import app, calculate, ChartRequest
from reporting import build_report

PROFILE = {'name':'नमुना कुण्डली','birth_date':'1990-01-01','birth_time':'12:00:00','place':'काठमाडौं, नेपाल','timezone':'Asia/Kathmandu','latitude':27.7,'longitude':85.3}

def chart(accuracy='exact'):
    return calculate(ChartRequest(birth_date='1990-01-01',birth_time=None if accuracy=='unknown' else '12:00',timezone='Asia/Kathmandu',latitude=27.7,longitude=85.3,accuracy=accuracy))

def test_searchable_pdf_embeds_fonts_and_chart_facts():
    result = build_report(PROFILE, chart())
    assert result.startswith(b'%PDF-')
    reader = PdfReader(BytesIO(result))
    assert 6 <= len(reader.pages) <= 8
    text = '\n'.join(p.extract_text() for p in reader.pages)
    assert 'नमुना' in text
    assert 'Aquarius' in text
    assert 'Vimshottari' in text
    assert 'cannot scientifically establish' in text
    assert b'/FontFile2' in result

def test_unknown_time_pdf_does_not_invent_positions():
    result = build_report(PROFILE, chart('unknown'))
    text = '\n'.join(p.extract_text() for p in PdfReader(BytesIO(result)).pages)
    assert 'No chart, Ascendant or dasha has been invented' in text
    assert 'Moon placement:' not in text

def test_pdf_endpoint_requires_service_auth(monkeypatch):
    monkeypatch.setenv('CALCULATOR_TOKEN','report-test-token')
    client = TestClient(app)
    assert client.post('/v1/reports',json={'profile':PROFILE,'chart':chart()}).status_code == 401
    response = client.post('/v1/reports',headers={'Authorization':'Bearer report-test-token'},json={'profile':PROFILE,'chart':chart()})
    assert response.status_code == 200
    assert response.headers['content-type'] == 'application/pdf'
    assert response.headers['cache-control'] == 'no-store'

def test_invalid_chart_is_rejected():
    with pytest.raises(ValueError):
        build_report(PROFILE, {'planets':[]})


def test_nepali_report_localizes_headings_and_rules():
    result = build_report({**PROFILE,'language':'ne'},chart())
    text = '\n'.join(p.extract_text() for p in PdfReader(BytesIO(result)).pages)
    assert 'जन्म विवरण र कुण्डली' in text
    assert 'चन्द्रस्थिति' in text
    assert 'अन्तर्दशाको विस्तृत परिशिष्ट' in text
    assert 'Planetary positions and planetary periods' not in text
    assert 'विंशोत्तरी महादशा समयरेखा' in text


def test_full_antardasha_appendix_includes_last_boundary():
    data=chart()
    result=build_report(PROFILE,data)
    text='\n'.join(p.extract_text() for p in PdfReader(BytesIO(result)).pages)
    assert data['dashas'][-1]['antardashas'][-1]['end'][:10] in text
    assert 'Full Antardasha appendix' in text


def test_north_indian_and_approximate_time_report():
    result=build_report({**PROFILE,'chart_style':'north'},chart('approximate'))
    text='\n'.join(p.extract_text() for p in PdfReader(BytesIO(result)).pages)
    assert 'Fixed houses' in text
    assert 'Approximate birth time' in text


def test_report_rejects_unsupported_chart_style():
    with pytest.raises(ValueError):
        build_report({**PROFILE,'chart_style':'invalid'},chart())

def test_pdf_records_provenance_and_sunrise_panchanga():
    data=chart()
    result=build_report(PROFILE,data)
    text='\n'.join(p.extract_text() for p in PdfReader(BytesIO(result)).pages)
    assert data['provenance']['calculator_source_sha256'] in text
    assert data['panchanga']['sunrise_day']['sunrise_local'] in text
    assert 'Traditional geometric' in text or 'geometric conditions' in text


def test_nepali_approximate_report_explains_sampled_uncertainty():
    result=build_report({**PROFILE,'language':'ne'},chart('approximate'))
    text=' '.join(' '.join(p.extract_text().split()) for p in PdfReader(BytesIO(result)).pages)
    assert 'अनुमानित समयको परीक्षण' in text
    assert 'सम्भावना होइन' in text
    assert 'गणना स्रोतको SHA-256' in text
