import sys, tempfile, unittest
from pathlib import Path
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'research'))
from research_engine import ResearchEngine
from connectors.url_pdf import TextHTMLParser, parse_upload

class ResearchTests(unittest.TestCase):
    def setUp(self):
        self.tmp=Path(tempfile.mkdtemp())
        (self.tmp/'data/cache').mkdir(parents=True)
        self.engine=ResearchEngine(self.tmp)
    def test_html_sections(self):
        p=TextHTMLParser();p.feed('<h1>Dose</h1><p>1 g every 8 hours</p><h2>Renal</h2><p>Adjust interval.</p>');p.flush()
        self.assertIn(('Dose','1 g every 8 hours'),p.blocks)
        self.assertIn(('Renal','Adjust interval.'),p.blocks)
    def test_csv_upload(self):
        import base64
        src=parse_upload('table.csv',base64.b64encode(b'Drug,Dose\nA,1 g').decode())
        self.assertEqual(src['sections'][0]['data']['Dose'],'1 g')
    def test_draft_claim_locator(self):
        sources=[{'connector':'dailymed','sourceType':'structured_product_label','title':'Label','url':'x','sourceVersion':'1','publicationDate':'2026','retrievedAt':'now','sections':[{'section':'Dosage and Administration','subsection':'Adult','locator':'SPL section code 34068-7','text':'1 g IV every 8 hours','sectionCode':'34068-7'}]}]
        claims=self.engine._draft_claims('Meropenem',sources)
        self.assertEqual(claims[0]['field'],'doseByIndication')
        self.assertEqual(claims[0]['evidenceDraft']['locator']['section'],'Dosage and Administration')
        self.assertTrue(claims[0]['evidenceDraft']['locator']['paragraphOrBullet'])
        self.assertEqual(claims[0]['reviewStage'],'source_attached')
    @patch('research_engine.rxnorm.research')
    @patch('research_engine.dailymed.research')
    @patch('research_engine.openfda.research')
    @patch('research_engine.pubmed.research')
    def test_orchestration_stays_draft(self,pub,ofd,dm,rx):
        rx.return_value=({'connector':'rxnorm','sections':[]},[{'rxcui':'123','name':'Meropenem 1 g injection'}])
        dm.return_value=[{'connector':'dailymed','sourceType':'structured_product_label','title':'Label','url':'x','sourceVersion':'1','publicationDate':'2026','retrievedAt':'now','sections':[{'section':'Contraindications','subsection':'','locator':'SPL section code 34070-3','text':'Hypersensitivity','sectionCode':'34070-3'}]}]
        ofd.return_value=[];pub.return_value={'connector':'pubmed','sections':[]}
        r=self.engine.run('Meropenem')
        self.assertEqual(r['draftClaims'][0]['validationStatus'],'draft')
        self.assertNotEqual(r['draftClaims'][0]['reviewStage'],'validated')
        self.assertIn('renalDosing',r['gaps'])

if __name__=='__main__': unittest.main()
