"""Offline team identity ingestion CLI. Run from app directory with Python 3.

No automatic internet access and no edits to football_analytics.db. Official
free datasets must be downloaded separately according to their licenses.
"""
import argparse
from pathlib import Path
import json
import team_identity_registry as registry

HERE=Path(__file__).resolve().parent


def main():
    p=argparse.ArgumentParser(description='Global football team identity registry')
    p.add_argument('--seed-local',action='store_true',help='Record names found in your existing match/queue databases (not verified aliases)')
    p.add_argument('--openfootball',metavar='DIRECTORY',help='Extracted openfootball/clubs folder, containing country *.txt files')
    p.add_argument('--reep',metavar='DIRECTORY',help='Extracted Reep v1 CSV bundle; not frozen v0 CSVs')
    p.add_argument('--csv',metavar='FILE',help='Normalized CSV: external_id,name,country,aliases etc')
    p.add_argument('--source',choices=registry.SOURCES,help='Source for --csv; from the ten free data sources')
    p.add_argument('--verified-reviewed',action='store_true',help='Only when each cross-team claim in --csv has been reviewed')
    p.add_argument('--stats',action='store_true')
    p.add_argument('--find',metavar='TEAM NAME',help='Test approved identity lookup')
    p.add_argument('--country',default='',help='Country context for --find')
    args=p.parse_args()
    outcomes=[]
    if args.seed_local:
        count=registry.local_observations(HERE/'football_analytics.db', HERE/'soccerrating_queue.db')
        outcomes.append({'localNameObservationsRead':count,'note':'Observations are not identity approvals'})
    if args.openfootball:outcomes.append(registry.import_openfootball(args.openfootball))
    if args.reep:outcomes.append(registry.import_reep_csv_bundle(args.reep))
    if args.csv:
        if not args.source:p.error('--csv needs --source')
        outcomes.append(registry.import_normalized_csv(
            args.csv,args.source,verified=args.verified_reviewed))
    if args.find:outcomes.append({'name':args.find,'country':args.country,
                                  'verifiedTeamId':registry.lookup(args.find,country=args.country)})
    if args.stats or not outcomes:outcomes.append(registry.stats())
    print(json.dumps(outcomes,ensure_ascii=False,indent=2))

if __name__=='__main__':main()
