# -*- coding: utf-8 -*-
# area-intel.json の文字列値内の未エスケープASCII二重引用符を全角” に置換して妥当なJSONへ修復。
import json, io, sys, shutil, tempfile, os
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
P = 'area-intel.json'
raw = open(P, encoding='utf-8').read()
STRUCT_PREV = set(':,{[')
STRUCT_NEXT = set(':,}]')
out = []
n = len(raw)
fixed = 0
for i, ch in enumerate(raw):
    if ch != '"':
        out.append(ch); continue
    if i > 0 and raw[i-1] == '\\':
        out.append(ch); continue
    j = i - 1
    while j >= 0 and raw[j] in ' \t\r\n':
        j -= 1
    prev = raw[j] if j >= 0 else None
    k = i + 1
    while k < n and raw[k] in ' \t\r\n':
        k += 1
    nxt = raw[k] if k < n else None
    structural = (prev in STRUCT_PREV) or (prev is None) or (nxt in STRUCT_NEXT)
    if structural:
        out.append(ch)
    else:
        out.append('”')  # inner quote -> full-width right double quote
        fixed += 1
repaired = ''.join(out)
try:
    obj = json.loads(repaired)
    shutil.copy(P, P + '.bak')
    fd, tmp = tempfile.mkstemp(dir='.', suffix='.tmp'); os.close(fd)
    json.dump(obj, open(tmp, 'w', encoding='utf-8'), ensure_ascii=False, indent=2)
    os.replace(tmp, P)
    secs = obj.get('sections', [])
    print("REPAIRED OK. inner-quotes fixed=%d | sections=%d | items=%d" % (
        fixed, len(secs), sum(len(s.get('items', [])) for s in secs)))
    for s in secs:
        print("  - %s | %s | %s | items=%d" % (s.get('id'), s.get('kind'), s.get('emoji'), len(s.get('items', []))))
except json.JSONDecodeError as e:
    print("STILL INVALID: %s" % e)
    print(repr(repaired[max(0, e.pos-70):e.pos+70]))
