"""Offline fixture checker. Reads explicit CSVs and regular local files only."""
import argparse,csv,hashlib,json,re,stat
from pathlib import Path
LIMITATIONS=[
 '元CRMでの台帳の網羅性・正しさは確認できない。両台帳から同じ添付が抜けると検出できない。',
 '基準SHA-256は移行前に独立取得した値が必要。移行後ファイルから作った値では元との一致を証明できない。',
 'バイト一致は閲覧可能性・業務上の内容の正しさ・元CRMの権限や関連の正しさを証明しない。',
 'URLは取得しない。リンク先の存在・期限・認証不要での閲覧は未確認。',
 '移行先CRMへの取り込み、履歴、添付以外の項目、元サービスを解約できるかは判定しない。',
 '静止したローカル検証用ファイルを対象とし、同時更新や敵対的なファイル置換への保証はない。'
]
def load_csv(path,required):
 with Path(path).open(encoding='utf-8-sig',newline='') as f:
  reader=csv.DictReader(f); cols=reader.fieldnames
  if not cols or len(cols)!=len(set(cols)) or any(not c.strip() for c in cols) or not set(required)<=set(cols):
   raise ValueError('missing/duplicate/empty CSV headers')
  rows=list(reader)
  if any(None in r or any(v is None for v in r.values()) for r in rows):raise ValueError('malformed CSV row')
  return rows

def check(expected_path,received_path,root):
 report={'status':'unknown','migration_approved':False,'findings':[],'limitations':LIMITATIONS}
 def add(kind,**extra):report['findings'].append({'kind':kind,**extra})
 try:
  expected=load_csv(expected_path,['record_id','attachment_id','sha256'])
  received=load_csv(received_path,['record_id','attachment_id','local_path','url'])
  root=Path(root)
  if root.is_symlink() or not root.is_dir():raise ValueError('root must be a local directory, not a symlink')
  root=root.resolve()
  if not expected:raise ValueError('empty expected manifest cannot establish completeness')
  def index(rows,which):
   result={}
   for r in rows:
    key=(r['record_id'],r['attachment_id'])
    if any(not v.strip() or v!=v.strip() for v in key) or key in result:raise ValueError(which+': missing/ambiguous/duplicate identity')
    result[key]=r
   return result
  exp=index(expected,'expected');got=index(received,'received')
  for key,r in exp.items():
   identity={'record_id':key[0],'attachment_id':key[1]}
   if not re.fullmatch('[0-9a-fA-F]{64}',r['sha256']):add('ledger_insufficient',**identity);continue
   if key not in got:add('missing_manifest_entry',**identity);continue
   item=got[key]; rel=item['local_path']
   if not rel:
    add('link_only' if item['url'].strip() else 'missing_local_file',**identity);continue
   p=Path(rel)
   if p.is_absolute() or '..' in p.parts or ':' in rel or '\\' in rel: add('unsafe_path',**identity);continue
   target=root
   unsafe=False
   for part in p.parts:
    target=target/part
    if target.is_symlink():unsafe=True;break
   if unsafe:add('unsafe_path',**identity);continue
   try:
    info=target.stat()
    if not stat.S_ISREG(info.st_mode):add('not_regular_file',**identity);continue
    if getattr(info,'st_flags',0)&0x40000000:add('file_unavailable',**identity);continue
    h=hashlib.sha256()
    with target.open('rb') as f:
     for block in iter(lambda:f.read(65536),b''):h.update(block)
    actual=h.hexdigest()
    add('matched' if actual==r['sha256'].lower() else 'content_mismatch',**identity,observed_sha256=actual)
   except FileNotFoundError:add('missing_local_file',**identity)
   except OSError:add('file_unavailable',**identity)
  for key in got.keys()-exp.keys():add('unlisted_attachment',record_id=key[0],attachment_id=key[1])
  kinds={r['kind'] for r in report['findings']}
  unknown={'ledger_insufficient','unsafe_path','not_regular_file','file_unavailable','unlisted_attachment'}
  report['status']='unknown' if kinds&unknown else ('matched_listed_bytes' if kinds=={'matched'} else 'discrepancy')
 except (OSError,ValueError,UnicodeError,csv.Error) as e:add('ledger_insufficient',reason=str(e))
 report['exit_code']={'matched_listed_bytes':0,'discrepancy':1,'unknown':2}[report['status']]
 return report
if __name__=='__main__':
 p=argparse.ArgumentParser();p.add_argument('expected');p.add_argument('received');p.add_argument('root');a=p.parse_args()
 r=check(a.expected,a.received,a.root);print(json.dumps(r,ensure_ascii=False,indent=2));raise SystemExit(r['exit_code'])
