"""Deterministic offline regression tests for Global Team Identity integration."""
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase, main
from unittest.mock import patch
import csv
import sqlite3
from contextlib import closing

import team_identity_registry as reg
import sr_fixture_identity as identity
import sr_fixture_verification as verified
import sr_four_free_recovery as recovery


class IdentityIntegrationTests(TestCase):
    def setUp(self):
        self.tmp=TemporaryDirectory()
        self.addCleanup(self.tmp.cleanup)
        self.db=Path(self.tmp.name)/'teams.db'
        reg.setup(self.db)
        with closing(reg.connection(self.db)) as c:
            reg.add_team(c,'OpenFootball Clubs','eng/manutd','Manchester United',
                         country='England',aliases=['Man Utd','Man United','Manchester United FC'],verified=True)
            reg.add_team(c,'OpenFootball Clubs','eng/liverpool','Liverpool FC',
                         country='England',aliases=['Liverpool'],verified=True)
            c.commit()
        reg._lookup_cached.cache_clear()
        self.fixture={'home':'Man Utd','away':'Liverpool','match_date':'2026-11-21',
                      'country':'England','league':'Premier League'}

    def aliases(self,h='Manchester United',a='Liverpool FC',country='England'):
        return reg.alias_map_for_fixture(self.fixture['home'],self.fixture['away'],h,a,
                                          country=country,path=self.db)

    def test_known_aliases_match_same_fixture(self):
        got=identity.source_fixture(self.fixture,'Manchester United','Liverpool FC','2026-11-21',
                    country='England',league='Premier League',aliases=self.aliases())
        self.assertEqual(got.classification,'match')
        self.assertEqual(got.home.classification,'verified_alias')
        self.assertEqual(got.away.classification,'verified_alias')

    def test_existing_engine_adapter_uses_registry_without_new_vote(self):
        real=reg.alias_map_for_fixture
        def hook(home,away,source_home,source_away,*,country=''):
            return real(home,away,source_home,source_away,country=country,path=self.db)
        with patch.object(verified.team_registry,'alias_map_for_fixture',side_effect=hook):
            got=verified._provider_event(self.fixture,'Manchester United','Liverpool FC','2026-11-21',
                                          country='England',league='Premier League')
        self.assertEqual(got.classification,'match')

    def test_existing_recovery_adapter_uses_registry(self):
        real=reg.alias_map_for_fixture
        def hook(home,away,source_home,source_away,*,country=''):
            return real(home,away,source_home,source_away,country=country,path=self.db)
        with patch.object(recovery.team_registry,'alias_map_for_fixture',side_effect=hook):
            rows=recovery._matching([{'home':'Manchester United','away':'Liverpool FC',
                                      'date':'2026-11-21'}],self.fixture)
        self.assertEqual(len(rows),1)
        self.assertEqual(rows[0]['_identity'],'match')

    def test_swapped_home_away_is_rejected(self):
        got=identity.source_fixture(self.fixture,'Liverpool FC','Manchester United','2026-11-21',
                    aliases=self.aliases('Manchester United','Liverpool FC'))
        self.assertEqual(got.classification,'reject')

    def test_other_date_is_rejected(self):
        got=identity.source_fixture(self.fixture,'Manchester United','Liverpool FC','2026-12-02',
                    aliases=self.aliases())
        self.assertEqual(got.classification,'reject')

    def test_competition_conflict_is_rejected(self):
        got=identity.source_fixture(self.fixture,'Manchester United','Liverpool FC','2026-11-21',
                    country='England',league='FA Cup',aliases=self.aliases())
        self.assertEqual(got.classification,'reject')

    def test_womens_and_reserves_are_not_merged(self):
        for bad in ['Manchester United Women','Manchester United B','Manchester United U21']:
            got=identity.source_fixture(self.fixture,bad,'Liverpool FC','2026-11-21',aliases=self.aliases())
            self.assertEqual(got.classification,'reject',bad)

    def test_name_conflict_abstains(self):
        with closing(reg.connection(self.db)) as c:
            reg.add_team(c,'OpenFootball Clubs','other/manutd','Manchester United',
                         country='England',aliases=['Man Utd'],verified=True)
            c.commit()
        reg._lookup_cached.cache_clear()
        self.assertIsNone(reg.lookup('Man Utd',country='England',path=self.db))

    def test_country_restriction_does_not_force_wrong_club(self):
        self.assertIsNone(reg.lookup('Man Utd',country='Spain',path=self.db))

    def test_proposed_womens_claim_blocks_unqualified_verified_senior_name(self):
        with closing(reg.connection(self.db)) as c:
            reg.add_team(c,'Reep','men/example','Example Town',
                         country='England',gender='men',
                         aliases=['Shared Example Town'],verified=True)
            reg.add_team(c,'Reep','women/example','Example Town Women',
                         country='England',category='women',gender='women',
                         aliases=['Shared Example Town'],verified=False)
            c.commit()
        reg._lookup_cached.cache_clear()
        self.assertIsNone(reg.lookup('Shared Example Town',country='England',path=self.db))
        self.assertIsNotNone(reg.lookup('Shared Example Town',country='England',
                                        gender='men',path=self.db))

    def test_other_country_reep_claim_requires_known_country(self):
        with closing(reg.connection(self.db)) as c:
            reg.add_team(c,'Reep','arg/manutd','Manchester United',
                         country='Argentina',aliases=['Man Utd'],verified=False)
            c.commit()
        reg._lookup_cached.cache_clear()
        self.assertIsNone(reg.lookup('Man Utd',path=self.db))
        self.assertIsNotNone(reg.lookup('Man Utd',country='England',path=self.db))

    def test_unverified_export_does_not_automatically_match(self):
        with closing(reg.connection(self.db)) as c:
            reg.add_team(c,'KickoffAPI','zz1','Invented Name',country='Ghana',
                         aliases=['Another Invented Name'],verified=False)
            c.commit()
        reg._lookup_cached.cache_clear()
        self.assertIsNone(reg.lookup('Another Invented Name',country='Ghana',path=self.db))

    def test_registry_changes_never_touch_main_database(self):
        source=Path(__file__).resolve().parent/'football_analytics.db'
        with closing(sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True)) as c:
            old=c.execute('SELECT COUNT(*) FROM matches').fetchone()[0]
        reg.stats(self.db)
        with closing(sqlite3.connect('file:'+str(source)+'?mode=ro',uri=True)) as c:
            self.assertEqual(c.execute('SELECT COUNT(*) FROM matches').fetchone()[0],old)

    def test_openfootball_parser_joins_variants_only_within_source_row(self):
        root=Path(self.tmp.name)/'clubs';(root/'europe').mkdir(parents=True)
        (root/'europe'/'england.txt').write_text(
            '= England\nArsenal FC, 1886, @ Emirates Stadium\n  | Arsenal | FC Arsenal\n'
            'Arsenal Women FC, 1987\n | Arsenal Women\n',encoding='utf-8')
        db=Path(self.tmp.name)/'openfootball.db'
        result=reg.import_openfootball(root,path=db)
        self.assertEqual(result['records'],2)
        self.assertIsNone(reg.lookup('FC Arsenal',country='England',path=db))
        self.assertIsNone(reg.lookup('Arsenal Women',country='England',path=db))
        with closing(reg.connection(db)) as c:
            values=c.execute('''SELECT a.team_id,a.status,a.name_key FROM aliases a
                WHERE a.name_key IN (?,?) ORDER BY a.name_key''',
                (reg.norm('FC Arsenal'),reg.norm('Arsenal Women'))).fetchall()
        self.assertEqual(len(values),2)
        self.assertEqual({v['status'] for v in values},{'proposed'})
        self.assertNotEqual(values[0]['team_id'],values[1]['team_id'])
        reg.import_openfootball(root,path=db)
        with closing(reg.connection(db)) as c:
            self.assertEqual(c.execute("SELECT count(*) FROM aliases WHERE status='verified'").fetchone()[0],0)

    def test_reep_v1_csv_loader(self):
        root=Path(self.tmp.name)/'reep';root.mkdir()
        samples={
          'entities.csv':(['reep_id','entity_type','canonical_name','gender','country'],[
              ['reep_t1','team','FC Sample','men','Ghana'],['reep_p1','person','Person A','men','Ghana']]),
          'provider_aliases.csv':(['reep_id','alias','provider'],[
              ['reep_t1','Sample FC','api_football']]),
          'bridges.csv':(['reep_id','provider','namespace','external_id'],[
              ['reep_t1','api_football','','123']]),
          'redirects.csv':(['from_id','to_id'],[])
        }
        for f,(header,rows) in samples.items():
            with (root/f).open('w',newline='',encoding='utf-8') as out:
                writer=csv.writer(out);writer.writerow(header);writer.writerows(rows)
        db=Path(self.tmp.name)/'reep.db'
        result=reg.import_reep_csv_bundle(root,path=db)
        self.assertEqual(result['teams'],1)
        self.assertIsNone(reg.lookup('Sample FC',country='Ghana',path=db))
        self.assertIsNone(reg.lookup('FC Sample',country='Ghana',path=db))
        with closing(reg.connection(db)) as c:
            values=c.execute('''SELECT team_id,status FROM aliases
                WHERE name_key IN (?,?) ORDER BY name_key''',
                (reg.norm('Sample FC'),reg.norm('FC Sample'))).fetchall()
        self.assertEqual(len(values),2)
        self.assertEqual({v['team_id'] for v in values},{reg._id('Reep','reep_t1')})
        self.assertEqual({v['status'] for v in values},{'proposed'})
        reg.import_reep_csv_bundle(root,path=db)
        with closing(reg.connection(db)) as c:
            self.assertEqual(c.execute("SELECT count(*) FROM aliases WHERE status='verified'").fetchone()[0],0)

    def test_discovery_query_is_bounded(self):
        queries=reg.discovery_queries('Man Utd','Liverpool',country='England',path=self.db)
        self.assertLessEqual(len(queries),2)
        self.assertEqual(queries[0],('Man Utd','Liverpool'))
        self.assertIn('Manchester United',queries[1][0])

if __name__=='__main__':main(verbosity=2)
