#!/usr/bin/env python3
"""NAT5 listed-company lead capture study. Run from any directory."""
import argparse, collections, csv, datetime as dt, json, random, re, sys, time
from pathlib import Path
from urllib.parse import urljoin, urlparse
from urllib.robotparser import RobotFileParser
import requests
from bs4 import BeautifulSoup

ROOT = Path(__file__).resolve().parent
PUBLIC = ROOT.parents[1] / 'public/research/lead-capture-2026'
UA = 'NAT5ResearchBot/1.0 (+https://nat5.com/research/)'
LIST = 'https://api.nasdaq.com/api/nordic/screener/shares'
WD = 'https://query.wikidata.org/sparql'
HEADERS = {'User-Agent': UA, 'Accept': 'text/html,application/json;q=0.9,*/*;q=0.8'}
SIGNALS = ['contact_form','meeting_booking','live_chat','visible_phone','visible_general_email','response_promise','sales_contact','llms_txt','organization_jsonld']
RULES = json.loads((ROOT/'rules.json').read_text())


def put(name, obj):
    (ROOT/name).write_text(json.dumps(obj, ensure_ascii=False, indent=2)+'\n', encoding='utf8')


def get(url, *, timeout=12, params=None, headers=None):
    return requests.get(url, params=params, headers=headers or HEADERS, timeout=timeout, allow_redirects=True)


def population():
    now = dt.datetime.now(dt.timezone.utc).isoformat()
    rows = []
    urls = []
    for seg in ['LARGE_CAP','MID_CAP','SMALL_CAP', 'FIRST_NORTH']:
        params = {'category': 'FIRST_NORTH' if seg == 'FIRST_NORTH' else 'MAIN_MARKET', 'market':'STO', 'tableonly':'true', 'page':1, 'size':1000, 'lang':'en'}
        if seg != 'FIRST_NORTH': params['segment'] = seg
        r = get(LIST, params=params, headers={'User-Agent':'Mozilla/5.0','Accept':'application/json'}, timeout=25)
        r.raise_for_status(); data = r.json()['data']['instrumentListing']['rows']; urls.append(r.url)
        for x in data:
            rows.append({'company':x['fullName'], 'segment':seg.replace('_CAP',' Cap').title().replace('First_North','First North'), 'sector':x.get('sector') or None, 'isin':x.get('isin'), 'symbol':x.get('symbol'), 'orderbook_id':x.get('orderbookId')})
    # Company share classes are merged by stem within a segment; keep the primary first ISIN.
    unique = {}
    for row in rows:
        stem = re.sub(r'\s+(?:A|B|C|D|PREF|PREF B|SDB)$', '', row['company'], flags=re.I)
        key = (row['segment'],stem.casefold())
        if key not in unique: unique[key] = {**row,'company':stem,'isins':[row['isin']]}
        else: unique[key]['isins'].append(row['isin'])
    companies = list(unique.values())
    meta = {'retrieved_utc':now,'listing_urls':urls,'raw_instrument_rows':len(rows),'deduplicated_companies':len(companies),'deduplication':'remove trailing share class A/B/C/D/PREF/SDB within segment; preserve all ISINs'}
    put('population.json',companies);put('source.json',meta)
    print('population',len(companies),'instrument rows',len(rows),flush=True)


def websites():
    companies = json.loads((ROOT/'population.json').read_text())
    all_isins = [isin for c in companies for isin in c['isins'] if isin]
    found={}
    for i in range(0,len(all_isins),65):
        chunk=all_isins[i:i+65]
        vals=' '.join(json.dumps(x) for x in chunk)
        query='SELECT ?isin ?item ?website WHERE { VALUES ?isin { '+vals+' } ?item wdt:P946 ?isin; wdt:P856 ?website. }'
        try:
            r=get(WD,params={'query':query,'format':'json'},headers={'User-Agent':UA,'Accept':'application/sparql-results+json'},timeout=60)
            r.raise_for_status()
            for b in r.json()['results']['bindings']:
                isin=b['isin']['value'];site=b['website']['value'];item=b['item']['value']
                if urlparse(site).scheme in ('http','https'):
                    found.setdefault(isin,[]).append({'url':site,'wikidata_item':item})
        except Exception as exc: print('wikidata batch failed',i,str(exc),file=sys.stderr,flush=True)
        time.sleep(1.5)
    for c in companies:
        matches=[hit for isin in c['isins'] for hit in found.get(isin,[])]
        domains={urlparse(x['url']).netloc.lower().removeprefix('www.') for x in matches}
        if len(domains)==1 and matches:
            c['url']=matches[0]['url'];c['website_source']='Wikidata P946 ISIN to P856 official website';c['website_source_url']=matches[0]['wikidata_item']
        else:
            c['url']=None;c['website_source']='unmatched' if not matches else 'ambiguous Wikidata domains'
    put('population.json',companies)
    print('website matches',sum(bool(c['url']) for c in companies),'of',len(companies),flush=True)


def websites_by_name():
    """Exact Wikidata English or Swedish label fallback; reject ambiguous items or domains."""
    companies=json.loads((ROOT/'population.json').read_text())
    unmatched=[c for c in companies if not c.get('url')]
    found=collections.defaultdict(list)
    for i in range(0,len(unmatched),45):
        chunk=unmatched[i:i+45]
        values=' '.join(f'{json.dumps(c["company"])}@{lang}' for c in chunk for lang in ('en','sv'))
        query='SELECT ?name ?item ?website WHERE { VALUES ?name { '+values+' } ?item rdfs:label ?name; wdt:P856 ?website. }'
        try:
            r=get(WD,params={'query':query,'format':'json'},headers={'User-Agent':UA,'Accept':'application/sparql-results+json'},timeout=60)
            r.raise_for_status()
            for b in r.json()['results']['bindings']:
                found[b['name']['value']].append({'url':b['website']['value'],'wikidata_item':b['item']['value']})
        except Exception as exc:print('name batch failed',i,str(exc),file=sys.stderr,flush=True)
        time.sleep(1.5)
    gained=0
    for c in unmatched:
        hits=found[c['company']]
        items={x['wikidata_item'] for x in hits}
        domains={urlparse(x['url']).netloc.lower().removeprefix('www.') for x in hits if urlparse(x['url']).scheme in ('http','https')}
        if len(items)==1 and len(domains)==1:
            c['url']=hits[0]['url'];c['website_source']='Wikidata exact English or Swedish company label to P856 official website';c['website_source_url']=hits[0]['wikidata_item'];gained+=1
    put('population.json',companies)
    print('additional exact name matches',gained,'total',sum(bool(c['url']) for c in companies),flush=True)
    validate_name()


def validate_name():
    """For label only matches, require Wikidata country to match the ISIN country."""
    companies=json.loads((ROOT/'population.json').read_text())
    selected=[c for c in companies if c.get('website_source','').startswith('Wikidata exact')]
    countries=collections.defaultdict(set)
    for i in range(0,len(selected),65):
        chunk=selected[i:i+65]
        values=' '.join('<'+c['website_source_url']+'>' for c in chunk)
        query='SELECT ?item ?country WHERE { VALUES ?item { '+values+' } OPTIONAL { ?item wdt:P17 ?country. } }'
        try:
            r=get(WD,params={'query':query,'format':'json'},headers={'User-Agent':UA,'Accept':'application/sparql-results+json'},timeout=60);r.raise_for_status()
            for b in r.json()['results']['bindings']:
                if 'country' in b:countries[b['item']['value']].add(b['country']['value'].split('/')[-1])
        except Exception as exc:print('country batch failed',i,str(exc),file=sys.stderr,flush=True)
        time.sleep(1.5)
    expected={'SE':'Q34','FI':'Q33','DK':'Q35','MT':'Q233','GB':'Q145','NO':'Q20','NL':'Q55','US':'Q30','IS':'Q189'}
    rejected=[]
    for c in selected:
        country=expected.get((c.get('isin') or '')[:2])
        if not country or country not in countries[c['website_source_url']]:
            rejected.append({'company':c['company'],'url':c['url'],'wikidata_country':sorted(countries[c['website_source_url']]),'expected_country':country})
            c['url']=None;c['website_source']='exact label rejected: Wikidata country does not match ISIN country'
    put('population.json',companies);put('rejected-name-matches.json',rejected)
    print('rejected name matches',len(rejected),'verified',sum(bool(c['url']) for c in companies),flush=True)


def apply_overrides():
    companies=json.loads((ROOT/'population.json').read_text())
    overrides={x['company']:x for x in json.loads((ROOT/'manual-overrides.json').read_text())}
    for c in companies:
        if c['company'] in overrides:
            item=overrides[c['company']]
            c['url']=item['url'];c['website_source']='issuer website or Nasdaq issuer release manual verification';c['website_source_url']=item['source_url']
    put('population.json',companies)
    path=ROOT/'crawl.jsonl'
    if path.exists():
        saved=[x for x in map(json.loads,path.read_text().splitlines())
               if x['company'] not in overrides or x.get('website_source_url')==overrides[x['company']]['source_url']]
        path.write_text(''.join(json.dumps(x,ensure_ascii=False)+'\n' for x in saved),encoding='utf8')
    print('manual issuer verified overrides',len(overrides),flush=True)


def text_scope(soup):
    for tag in soup(['script','style','noscript','template','svg']): tag.decompose()
    for tag in soup.select('[hidden], [aria-hidden="true"], [style*="display:none"], [style*="display: none"]'): tag.decompose()
    return soup.get_text(' ',strip=True)


def booking_url(url):
    parsed=urlparse('https:'+url if url.startswith('//') else url)
    if parsed.scheme not in ('http','https'):return False
    host=(parsed.hostname or '').lower();path=parsed.path.lower()
    for item in RULES['booking_domains']:
        domain,_,required=item.partition('/')
        if (host==domain or host.endswith('.'+domain)) and (not required or path.startswith('/'+required)):
            return True
    return False


def detect(htmls):
    out={k:False for k in SIGNALS if k not in ('llms_txt',)}
    evidence={}
    for html in htmls:
        soup=BeautifulSoup(html,'html.parser')
        visible=BeautifulSoup(html,'html.parser'); text=text_scope(visible)
        for form in soup.find_all('form'):
            inputs=form.find_all(['input','textarea'])
            email=any(x.get('type')=='email' or re.search(r'email|e-?post',str(x.get('name',''))+' '+str(x.get('id','')),re.I) for x in inputs)
            message=any(x.name=='textarea' or re.search(r'message|meddelande|comment|fråga',str(x.get('name',''))+' '+str(x.get('id','')),re.I) for x in inputs)
            if email and message: out['contact_form']=True
        if any(booking_url(str(x.get('src',''))) for x in soup.find_all('script')) or any(booking_url(str(x.get('href',''))) for x in soup.find_all('a')):out['meeting_booking']=True
        script_urls=[str(x.get('src','')) for x in soup.find_all('script') if x.get('src')]
        if any(any(domain in src.lower() for domain in RULES['chat_script_domains']) or
               ('/icons/' not in src.lower() and 'chat-bubble' not in src.lower() and re.search(r'(?:chatbot|livechat|chatwidget|botwidget|/chat[./_-])',src,re.I))
               for src in script_urls):out['live_chat']=True
        phone_matches=re.finditer(r'(?<!\d)(?:\+\d{1,3}[\s()\-]*|0)(?:\(?\d[\d\s()\-]{5,18}\d)',text)
        if any(len(re.sub(r'\D','',match.group()))>=8 for match in phone_matches):out['visible_phone']=True
        general=r'(?:info|contact|sales|hello|support|kundservice|kundtjanst|reception|office)@'
        if re.search(general,text,re.I):out['visible_general_email']=True
        promise=re.compile(r'(?:svarar|återkommer|återkopplar|hör av oss|respons|respond|response|reply|get back to you).{0,45}(?:inom|within).{0,20}(?:\d{1,2}|one|two|en|ett).{0,15}(?:tim|hour|dag|day)',re.I)
        for match in promise.finditer(text):
            context=text[max(0,match.start()-110):match.end()+40]
            if not re.search(r'serviceanmälan|felanmälan|supportärende|privacy|personuppgift',context,re.I):out['response_promise']=True
        sales_pattern=r'(?:kontakta|kontakt|contact|talk|speak|prata|reach|meet).{0,35}(?:sälj\w*|sales|försäljning)|(?:sales|sälj\w*|försäljning).{0,25}(?:contact|kontakt)'
        if any(re.search(sales_pattern,x.get_text(' ',strip=True),re.I) for x in visible.find_all(['a','button','h1','h2','h3','h4'])):out['sales_contact']=True
        for node in soup.select('script[type="application/ld+json"]'):
            try: data=json.loads(node.string or node.get_text())
            except (ValueError,TypeError):continue
            stack=[data]
            while stack:
                x=stack.pop()
                if isinstance(x,list):stack.extend(x)
                elif isinstance(x,dict):
                    typ=x.get('@type',[])
                    types=typ if isinstance(typ,list) else [typ]
                    if any(str(t).rstrip('/').split('/')[-1]=='Organization' for t in types):out['organization_jsonld']=True
                    stack.extend(v for k,v in x.items() if k=='@graph')
    return out


def robots_policy(text, agent):
    # Root path only. The file itself is retained for a manual audit of ambiguous rules.
    groups=[]; current_agents=[]; rules=[]
    for line in text.splitlines():
        line=line.split('#',1)[0].strip()
        if not line or ':' not in line: continue
        k,v=(x.strip() for x in line.split(':',1));k=k.lower()
        if k=='user-agent':
            if rules:groups.append((current_agents,rules));current_agents=[];rules=[]
            current_agents.append(v.lower())
        elif k in ('allow','disallow') and current_agents:rules.append((k,v))
    if current_agents:groups.append((current_agents,rules))
    choices=[(agents,rules) for agents,rules in groups if agent.lower() in agents]
    if not choices:choices=[(agents,rules) for agents,rules in groups if '*' in agents]
    if not choices:return 'unspecified'
    matches=[(len(v),k,v) for _,rules in choices for k,v in rules if v and '/'.startswith(v.rstrip('*'))]
    if not matches:return 'allowed'
    matches.sort(key=lambda x:(x[0],x[1]=='allow'),reverse=True)
    return 'blocked' if matches[0][1]=='disallow' else 'allowed'


def crawl():
    companies=json.loads((ROOT/'population.json').read_text()); existing={}
    path=ROOT/'crawl.jsonl';raw=ROOT/'raw';raw.mkdir(exist_ok=True)
    if path.exists():
        current={c['company']+'|'+c['segment']:c for c in companies}
        saved=[]
        for x in map(json.loads,path.read_text().splitlines()):
            company=current[x['company']+'|'+x['segment']]
            if x['status']=='no_verified_url' and company.get('url'):continue
            if x['status']!='no_verified_url' and not company.get('url'):continue
            saved.append(x)
        path.write_text(''.join(json.dumps(x,ensure_ascii=False)+'\n' for x in saved),encoding='utf8')
        existing={x['company']+'|'+x['segment']:x for x in saved}
    last=0.0
    def polite(url,robot=None):
        nonlocal last
        host=urlparse(url).netloc
        if robot is not None and not robot.can_fetch(UA,url):return None,'robots_denied'
        interval=max(1.5,robot.crawl_delay(UA) or 0) if robot else 1.5
        delay=max(0,interval-(time.monotonic()-last));time.sleep(delay);last=time.monotonic()
        try:
            r=get(url,timeout=12)
            if r.status_code!=200:return None,'http_'+str(r.status_code)
            if len(r.content)>2_000_000:return None,'oversize'
            return r,None
        except requests.RequestException as e:return None,type(e).__name__
    with path.open('a',encoding='utf8') as f:
      for index,c in enumerate(companies):
        key=c['company']+'|'+c['segment']
        if key in existing:continue
        row={k:c.get(k) for k in ['company','segment','sector','url','website_source','website_source_url']}; row['checked_utc']=dt.datetime.now(dt.timezone.utc).isoformat()
        row['signals']={k:False for k in SIGNALS};row['robots']={a:'unknown' for a in RULES['robots_agents']};row['status']='no_verified_url'
        if c.get('url'):
          base=c['url']; parsed=urlparse(base);origin=f'{parsed.scheme}://{parsed.netloc}'
          rr,error=polite(origin+'/robots.txt')
          if rr:
            rp=RobotFileParser();rp.parse(rr.text.splitlines())
            row['robots']={a:robots_policy(rr.text,a) for a in RULES['robots_agents']}
            # Save only robots policy, no raw text needed.
          elif error=='http_404':
            rp=RobotFileParser();rp.parse([]);row['robots']={a:'unspecified' for a in RULES['robots_agents']}
          else:
            rp=None;row['robots_error']=error
          if rp and rp.can_fetch(UA,base):
            response,error=polite(base,rp)
            if response and 'html' in response.headers.get('content-type','').lower():
              home=response.text;htmls=[home];row['url']=response.url;row['status']='fetched';row['contact_page']=None
              soup=BeautifulSoup(home,'html.parser')
              for a in soup.find_all('a',href=True):
                label=a.get_text(' ',strip=True)
                if re.search(RULES['contact_link_text'],label,re.I):
                  candidate=urljoin(response.url,a['href'])
                  if urlparse(candidate).netloc==urlparse(response.url).netloc and candidate.rstrip('/')!=response.url.rstrip('/') and rp.can_fetch(UA,candidate):
                    cr,ce=polite(candidate,rp)
                    if cr and 'html' in cr.headers.get('content-type','').lower():htmls.append(cr.text);row['contact_page']=cr.url
                  break
              row['signals'].update(detect(htmls))
              # Raw HTML is kept outside Git for the 30 site human spot check only.
              safe=re.sub(r'[^A-Za-z0-9]+','_',key)[:90]
              (raw/(safe+'.json')).write_text(json.dumps({'home':home,'contact':htmls[1] if len(htmls)>1 else None,'robots':rr.text if rr else None}),encoding='utf8')
              ll,le=polite(origin+'/llms.txt',rp)
              row['llms_content_type']=ll.headers.get('content-type','') if ll else None
              row['signals']['llms_txt']=bool(ll and any(t in ll.headers.get('content-type','').lower() for t in ('text/plain','text/markdown')))
            else:row['status']=error or 'non_html'
          elif rp:row['status']='robots_denied'
          else:row['status']='robots_unknown'
        f.write(json.dumps(row,ensure_ascii=False)+'\n');f.flush()
        if (index+1)%20==0:print('processed',index+1,'of',len(companies),flush=True)
    print('crawl complete',len(companies),flush=True)


def analyse():
    population=json.loads((ROOT/'population.json').read_text());rows=[json.loads(x) for x in (ROOT/'crawl.jsonl').read_text().splitlines()]
    keys=[r['company']+'|'+r['segment'] for r in rows]
    if len(rows)!=len(population) or len(set(keys))!=len(population):
        raise RuntimeError(f'incomplete or duplicate crawl: {len(rows)} rows for {len(population)} companies')
    included=[r for r in rows if r['status']=='fetched']
    def group(items):
        n=len(items)
        def cell(k):return {'numerator':k,'denominator':n,'percent':round(100*k/n,2) if n else None}
        return {'denominator':n,
                'metrics':{key:cell(sum(bool(r['signals'][key]) for r in items)) for key in SIGNALS},
                'robots':{a:{v:sum(r['robots'][a]==v for r in items) for v in ['allowed','blocked','unspecified','unknown']} for a in RULES['robots_agents']},
                'robots_shares':{a:{v:cell(sum(r['robots'][a]==v for r in items)) for v in ['allowed','blocked','unspecified','unknown']} for a in RULES['robots_agents']}}
    groups={'all':group(included)}
    for seg in ['Large Cap','Mid Cap','Small Cap','First North']:groups[seg]=group([r for r in included if r['segment']==seg])
    for sector in sorted({r['sector'] for r in included if r['sector']}):groups['sector:'+sector]=group([r for r in included if r['sector']==sector])
    result={'source_date_utc':json.loads((ROOT/'source.json').read_text())['retrieved_utc'],'analysis_date_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'population':len(population),'website_verified':sum(bool(x.get('url')) for x in population),'without_verified_website':sum(not x.get('url') for x in population),'crawl_status':dict(collections.Counter(r['status'] for r in rows)),'groups':groups}
    put('results.json',result);PUBLIC.mkdir(parents=True,exist_ok=True)
    (PUBLIC/'results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
    with (PUBLIC/'companies.csv').open('w',newline='',encoding='utf8') as f:
        fields=['company','segment','sector','url','status']+SIGNALS+[a.lower()+'_robots' for a in RULES['robots_agents']]
        w=csv.DictWriter(f,fieldnames=fields,lineterminator='\n');w.writeheader()
        for r in rows:
            flags=r['signals'] if r['status']=='fetched' else {k:'' for k in SIGNALS}
            w.writerow({**{k:r.get(k) for k in fields[:5]},**flags,**{a.lower()+'_robots':r['robots'][a] for a in RULES['robots_agents']}})
    (PUBLIC/'rules.json').write_text((ROOT/'rules.json').read_text(),encoding='utf8')
    (PUBLIC/'population.json').write_text((ROOT/'population.json').read_text(),encoding='utf8')
    (PUBLIC/'source.json').write_text((ROOT/'source.json').read_text(),encoding='utf8')
    (PUBLIC/'study.py').write_text((ROOT/'study.py').read_text(),encoding='utf8')
    (PUBLIC/'manual-overrides.json').write_text((ROOT/'manual-overrides.json').read_text(),encoding='utf8')
    (PUBLIC/'rejected-name-matches.json').write_text((ROOT/'rejected-name-matches.json').read_text(),encoding='utf8')
    print(json.dumps({k:result[k] for k in ['population','website_verified','without_verified_website','crawl_status']},indent=2),flush=True)


def reclassify():
    path=ROOT/'crawl.jsonl'
    rows=[json.loads(x) for x in path.read_text().splitlines()]
    for row in rows:
        if row['status']!='fetched':continue
        key=row['company']+'|'+row['segment']
        safe=re.sub(r'[^A-Za-z0-9]+','_',key)[:90]
        raw=json.loads((ROOT/'raw'/(safe+'.json')).read_text())
        row['signals'].update(detect([raw['home']]+([raw['contact']] if raw['contact'] else [])))
        if row['signals']['llms_txt'] and 'llms_content_type' not in row:
            row['signals']['llms_txt']=False
            row['llms_pilot_unverified']=True
    path.write_text(''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in rows),encoding='utf8')
    print('reclassified',sum(r['status']=='fetched' for r in rows),flush=True)


def sample():
    rows=[json.loads(x) for x in (ROOT/'crawl.jsonl').read_text().splitlines() if x.strip()]
    included=sorted((r for r in rows if r['status']=='fetched'),key=lambda r:(r['company'],r['segment']));rng=random.Random(20261006)
    selected=rng.sample(included,min(30,len(included)))
    put('spotcheck-sample.json',[{'company':r['company'],'segment':r['segment'],'url':r['url'],'contact_page':r.get('contact_page'),'signals':r['signals'],'llms_content_type':r.get('llms_content_type'),'robots':r['robots']} for r in selected])
    print('sample',len(selected),flush=True)

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('command',choices=['population','websites','websites_by_name','validate_name','apply_overrides','crawl','analyse','sample','reclassify']);a=p.parse_args();globals()[a.command]()
