"""Classically encode one byte, teleport its 12-bit codeword, decode Bob's readouts."""
import getpass
import logging
import sys
import traceback
from collections import Counter
from pathlib import Path

from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.accounts.exceptions import InvalidAccountError

from graph156 import save
from run_switch_puzzles import ROOT, SHOTS, execute, load
from teleport_ascii_a import VALUE, circuit, prepare, triples

WIDTH=12
PARITY=(1,2,4,8)
DATA=tuple(i for i in range(1,WIDTH+1) if i not in PARITY)
SIM=ROOT/"Hamming-A-simulator.json"
HW=ROOT/"Hamming-A-Kingston.json"
TAG="hamming12-8-ascii-A-kingston-20261120"


def syndrome(word):
    check=0
    for i in range(1,WIDTH+1):
        if word & (1<<(i-1)):
            check^=i
    return check


def encode(byte):
    word=sum(((byte>>j)&1)<<(i-1) for j,i in enumerate(DATA))
    check=syndrome(word)
    return word+sum(1<<(i-1) for i in PARITY if i&check)


def payload(word):
    return sum(((word>>(i-1))&1)<<j for j,i in enumerate(DATA))


def decode(word):
    check=syndrome(word)
    if check>WIDTH:
        return None
    if check:
        word^=1<<(check-1)
    return payload(word)


def analyze(counts):
    raw=correct=rescued=lost=flags=0
    distances=Counter()
    words=Counter()
    for bits,n in counts.items():
        assert len(bits)==3*WIDTH and set(bits)<={"0","1"}
        word=int(bits,2)>>(2*WIDTH)
        before=payload(word)==VALUE
        after=decode(word)
        good=after==VALUE
        words[format(word,"012b")]+=n
        distances[(word^encode(VALUE)).bit_count()]+=n
        raw+=n*before
        correct+=n*good
        rescued+=n*(good and not before)
        lost+=n*(before and not good)
        flags+=n*(after is None)
    assert sum(counts.values())==SHOTS and raw+rescued-lost==correct
    return dict(raw_byte_exact=raw,decoded_byte_exact=correct,rescued=rescued,lost=lost,
                uncorrectable_flags=flags,wrong_returned=SHOTS-correct-flags,
                received_words=dict(words),codeword_bit_errors=dict(sorted(distances.items())))


def simulate():
    for b in range(256):
        w=encode(b)
        assert syndrome(w)==0 and decode(w)==b
        assert all(decode(w^(1<<j))==b for j in range(WIDTH))
    q=circuit("teleport",value=encode(VALUE),width=WIDTH)
    counts=AerSimulator(method="stabilizer").run(q,shots=SHOTS,seed_simulator=20261120).result().get_counts()
    result=analyze(counts)
    assert result["raw_byte_exact"]==result["decoded_byte_exact"]==SHOTS
    save(SIM,dict(ideal_shots=SHOTS,analysis=result,all_single_bit_decoder_tests_passed=256*WIDTH))
    print(result)


def hardware():
    rec=load(HW)
    if rec.get("analysis"):
        return
    if not sys.stdin.isatty() or not SIM.exists():
        raise RuntimeError("Complete simulation and use a private console")
    while True:
        key=getpass.getpass("IBM Cloud API key (hidden): ").strip()
        if not key:
            return
        try:
            service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,
                                         plans_preference=["open"],region="us-east")
            break
        except InvalidAccountError:
            print("Instance lookup failed. Paste the key again or press Enter to exit.")
    backend=service.backend("ibm_kingston")
    isa=[]
    if not rec:
        previous=load(ROOT/"ASCII-A-Kingston.json")
        data_paths=previous["triples_from_least_significant_bit"]
        reserved={q for p in data_paths for q in p}
        parity_paths=triples(backend,len(PARITY),reserved)
        by_position=dict(zip(DATA,data_paths))
        by_position.update(zip(PARITY,parity_paths))
        paths=[by_position[i] for i in range(1,13)]
        assert len({q for p in paths for q in p})==36
        _,fast,isa=prepare(backend,paths,("teleport",),encode(VALUE))
        rec=dict(backend=backend.name,input="A",codeword_positions_12_to_1=format(encode(VALUE),"012b"),
                 data_positions_lsb_first=DATA,triples_by_position=paths,previous_byte_job=previous["job_id"],
                 fast_mid_measure=fast,native_counts=dict(isa[0].count_ops()),
                 policy="Flip position 1..12 on a matching syndrome. Flag 13..15 and count as unsuccessful.")
    rec=execute(service,backend,HW,TAG,rec,lambda:isa)
    rec["analysis"]=analyze(rec["counts"][0])
    save(HW,rec)


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
            save(ROOT.parent/"work"/"hamming-a-error.json",{"type":type(exc).__name__,"frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")
