"""NEC winner XML collector. Python standard library only.
Run: python nec_collect.py
Use the official code-information service to confirm election ID/type codes.
API key is entered invisibly and never written to output files.
Authenticated response has not been tested without a user-issued key.
"""
import csv, getpass, hashlib, json, time
from pathlib import Path
from datetime import datetime, timezone
from urllib.parse import urlencode, unquote
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
import xml.etree.ElementTree as ET
ENDPOINT='https://apis.data.go.kr/9760000/WinnerInfoInqireService2/getWinnerInfoInqire'
def parse_response(raw):
    root=ET.fromstring(raw)
    for e in root.iter(): e.tag=e.tag.split('}')[-1]
    code=root.findtext('.//resultCode')
    if code not in ('INFO-00','00','0'): raise ValueError('API did not return success. Check approval/key/code parameters in the official portal.')
    total=int(root.findtext('.//totalCount') or 0)
    items=[{e.tag:e.text or '' for e in item} for item in root.findall('.//items/item')]
    return total,items

def main():
    key=getpass.getpass('Decoded service key (hidden): ').strip()
    election=input('Election ID (confirm official code, e.g. 20220601): ').strip()
    kind=input('Official election type code (metropolitan OR basic head): ').strip()
    if not key or not election or not kind: raise SystemExit('All three inputs are required.')
    stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    out=Path('nec_'+stamp);out.mkdir();items=[];hashes=[];expected=None
    try:
        for page in range(1,1001):
            query=urlencode({'serviceKey':unquote(key),'sgId':election,'sgTypecode':kind,'pageNo':page,'numOfRows':100,'resultType':'xml'})
            with urlopen(ENDPOINT+'?'+query,timeout=30) as response:raw=response.read()
            total,rows=parse_response(raw)
            if expected is None:expected=total
            elif total!=expected:raise ValueError('totalCount changed while collecting. Retry as a new collection.')
            name=f'page_{page:04d}.xml';(out/name).write_bytes(raw)
            hashes.append({'filename':name,'sha256':hashlib.sha256(raw).hexdigest()})
            if not rows and len(items)<total:raise ValueError('Unexpected empty page before totalCount reached.')
            items.extend(rows)
            if len(items)>=total:break
            time.sleep(.3)
        else:raise ValueError('Page limit reached; collection incomplete.')
        if len(items)!=expected:raise ValueError('Row count does not match totalCount.')
        columns=sorted({k for row in items for k in row})
        with (out/'winners.csv').open('w',encoding='utf-8-sig',newline='') as f:
            writer=csv.DictWriter(f,fieldnames=columns);writer.writeheader();writer.writerows(items)
        (out/'manifest.json').write_text(json.dumps({'endpoint':ENDPOINT,'election':election,'type_code':kind,'retrieved_utc':stamp,'rows':len(items),'files':hashes,'note':'Candidate ID is not a guaranteed cross-election person ID; verify office tenure separately.'},ensure_ascii=False,indent=2),encoding='utf-8')
        print('Saved',len(items),'rows to',out)
    except (HTTPError,URLError,ET.ParseError,ValueError,TimeoutError):
        raise SystemExit('Collection failed. Partial raw files retained. Check official approval, code values, API status and page counts. No URL/key is logged.')
if __name__=='__main__':main()
