import unittest,tempfile,os,time,sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
import core
from analysis import analyse,demo_data,render
from bot import csv_names,handle
class CoreTests(unittest.TestCase):
    def setUp(self):
        self.tmp=tempfile.TemporaryDirectory();core.DB=self.tmp.name+'/test.db';os.environ['OWNER_TELEGRAM_ID']='1';os.environ['PLAN_DAYS']='30';os.environ['PLAN_QUOTA']='30';core.init();core.register(2,'Player')
    def tearDown(self):self.tmp.cleanup()
    def test_permission(self):
        with self.assertRaises(PermissionError):core.admin_change(2,3)
        core.admin_change(1,3);self.assertTrue(core.is_admin(3));core.admin_change(1,3,False);self.assertFalse(core.is_admin(3))
    def test_approve_once(self):
        p=core.receipt(2,'photo','unique');core.review(1,p,True)
        self.assertEqual(core.user(2)['quota'],30)
        with self.assertRaises(ValueError):core.review(1,p,True)
        self.assertEqual(core.user(2)['quota'],30)
    def test_unauthorized_review(self):
        p=core.receipt(2,'a','b')
        with self.assertRaises(PermissionError):core.review(2,p,True)
        self.assertEqual(core.user(2)['quota'],0)
    def test_reject_no_subscription(self):
        p=core.receipt(2,'a','b');core.review(1,p,False,'عدم تطبیق');self.assertEqual(core.user(2)['quota'],0)
    def test_duplicate_photo(self):
        p=core.receipt(2,'a','b');core.review(1,p,False)
        with self.assertRaises(ValueError):core.receipt(2,'a','b')
    def test_one_pending(self):
        core.receipt(2,'a','b')
        with self.assertRaises(ValueError):core.receipt(2,'c','d')
    def test_renew_extends(self):
        p=core.receipt(2,'a','b');core.review(1,p,True);exp=core.user(2)['expires']
        q=core.receipt(2,'c','d');core.review(1,q,True);self.assertEqual(core.user(2)['expires'],exp+30*86400)
    def test_quota(self):
        with self.assertRaises(ValueError):core.reserve(2)
        p=core.receipt(2,'a','b');core.review(1,p,True);core.reserve(2);self.assertEqual(core.user(2)['quota'],29);core.refund(2);self.assertEqual(core.user(2)['quota'],30)
    def test_expired(self):
        with core.conn() as c:c.execute('UPDATE users SET quota=30,expires=1 WHERE id=2')
        with self.assertRaises(ValueError):core.reserve(2)
    def test_delete(self):
        core.account(2,'Name#TAG','EUW1');core.put_cache(2,{'games':[]});core.delete_profile(2);self.assertIsNone(core.user(2)['riot_id']);self.assertIsNone(core.cached(2))
    def test_changed_account_invalidates_cache(self):
        core.put_cache(2,{'games':[]});core.account(2,'Other#TAG','EUW1');self.assertIsNone(core.cached(2))
    def test_no_data_not_fabricated(self):
        result=analyse(demo_data(),'Teemo','TOP');self.assertEqual(result['m']['n'],0);self.assertEqual(result['confidence'],'بدون نمونه')
    def test_filtered_metrics(self):
        result=analyse(demo_data(),'Garen','TOP');self.assertEqual(result['m']['n'],14)
    def test_html_escaping(self):
        data=demo_data();data['riot_id']='<script>alert(1)</script>';html=render(data);self.assertIn('&lt;script&gt;',html);self.assertNotIn('<script>alert(1)</script>',html)
    def test_csv(self):
        self.assertEqual(csv_names('malphite, Lee Sin'),['Malphite','LeeSin'])
        with self.assertRaises(ValueError):csv_names('<script>')
        with self.assertRaises(ValueError):csv_names('Garen,Garen')
    def test_failed_analysis_refunds(self):
        from bot import run_analysis
        core.account(2,'Name#TAG','EUW1');p=core.receipt(2,'a','b');core.review(1,p,True)
        core.put_cache(2,demo_data())
        class FailedTelegram:
            def send(self,*args):pass
            def document(self,*args):raise RuntimeError('failed')
        with self.assertRaises(RuntimeError):run_analysis(FailedTelegram(),2,'/analyze')
        self.assertEqual(core.user(2)['quota'],30)
if __name__=='__main__':unittest.main()
