#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, os, math, re
import pandas as pd, numpy as np
D = os.path.dirname(os.path.abspath(__file__))
OUT = {}
def jload(p):
    with open(p, encoding='utf-8') as f: return json.load(f)

# ---- T86 proper field parsing ----
def t86(path):
    d = jload(path)
    if d.get('stat') != 'OK': return {'err': d.get('stat')}
    res = {}
    for r in d.get('data', []):
        code = str(r[0]).strip()
        if code in ('6669','00412A'):
            g = lambda i: r[i].replace(',','') if isinstance(r[i],str) else r[i]
            res[code] = {'name': r[1].strip(),
                'foreign': int(g(4)), 'dealer_total': int(g(11)),
                'trust': int(g(10)), 'dealer_self': int(g(14)),
                'dealer_hedge': int(g(17)), 'total': int(g(18))}
    return res
OUT['t86_1105'] = t86(os.path.join(D,'t86_20261105.json'))
OUT['t86_1104'] = t86(os.path.join(D,'t86_20261104.json'))

# ---- TWSE intraday for 6669 / 00412A latest ----
def stock_day(stock, months):
    rows=[]
    for m in months:
        p=os.path.join(D,f"{stock}_{m}.json")
        if not os.path.exists(p): continue
        d=jload(p)
        if d.get('stat')!='OK': continue
        for r in d.get('data',[]):
            y,mo,dd=str(r[0]).strip().split('/')
            def num(x):
                x=str(x).replace(',','').strip()
                try: return float(x)
                except: return np.nan
            rows.append(dict(date=pd.Timestamp(int(y)+1911,int(mo),int(dd)),volume=num(r[1]),
                open=num(r[3]),high=num(r[4]),low=num(r[5]),close=num(r[6]),change=num(r[7])))
    df=pd.DataFrame(rows).drop_duplicates(subset=['date']).sort_values('date').reset_index(drop=True)
    return df
tw=stock_day('6669',['20261001','20261101'])
tw['adj']=tw['date']<pd.Timestamp('2026-09-02')
for c in ('open','high','low','close'): tw.loc[tw['adj'],c]/=3.0
OUT['6669_today']=tw.iloc[-1].to_dict()
OUT['6669_prev']=tw.iloc[-2].to_dict()
OUT['6669_prev2']=tw.iloc[-3].to_dict()
e=stock_day('00412A',['20261001','20261101'])
OUT['00412A_today']=e.iloc[-1].to_dict()
OUT['00412A_prev']=e.iloc[-2].to_dict()
OUT['00412A_v10']=float(e['volume'].tail(10).mean())
OUT['00412A_vlast10']=e['volume'].tail(10).tolist()
OUT['00412A_dates']=[str(x.date()) for x in e['date']]
OUT['00412A_closes']=e['close'].tolist()
OUT['00412A_vol_ratio_10']=float(e['volume'].iloc[-1]/e['volume'].tail(10).mean())
OUT['00412A_from_high_pct']=float((e['close'].iloc[-1]-e['high'].max())/e['high'].max()*100)
OUT['00412A_n_days']=len(e)

# ---- Yahoo peers full ----
def yahoo(path):
    try: d=jload(path)
    except Exception as ex: return None
    try: r=d['chart']['result'][0]
    except Exception: return None
    ts=r.get('timestamp') or []
    q=r['indicators']['quote'][0]
    adj=(r['indicators'].get('adjclose') or [{}])[0].get('adjclose')
    rows=[]
    for i,t in enumerate(ts):
        c=q['close'][i]
        if c is None or (isinstance(c,float) and math.isnan(c)): continue
        if adj and adj[i] is not None and not (isinstance(adj[i],float) and math.isnan(adj[i])): c=adj[i]
        rows.append(dict(date=pd.Timestamp(t,unit='s').tz_localize(None).normalize(),
            open=q['open'][i],high=q['high'][i],low=q['low'][i],close=c,volume=q['volume'][i] or 0))
    df=pd.DataFrame(rows)
    if len(df): df=df.drop_duplicates(subset=['date']).sort_values('date').reset_index(drop=True)
    return df
def peer(key,label):
    df=yahoo(os.path.join(D,f'yahoo_{key}.json'))
    if df is None or not len(df): OUT[label]={'err':'empty'}; return
    df=df.reset_index(drop=True)
    last=df.iloc[-1]
    OUT[label]={'date':str(last['date'].date()),'close':round(float(last['close']),2),
        'chg1':round(float((last['close']/df['close'].iloc[-2]-1)*100),2),
        'chg3':round(float((last['close']/df['close'].iloc[-4]-1)*100),2),
        'chg5':round(float((last['close']/df['close'].iloc[-6]-1)*100),2),
        'high60':round(float(df['close'].tail(60).max()),2),'low60':round(float(df['close'].tail(60).min()),2),
        'from_high60_pct':round(float((last['close']-df['close'].tail(60).max())/df['close'].tail(60).max()*100),2),
        'last3dates':[str(x.date()) for x in df['date'].tail(3)]}
for k,l in [('%5ESOX','sox'),('AMZN','amzn'),('MSFT','msft'),('GOOGL','googl'),
            ('2330.TW','tsmc'),('2344.TW','winbond'),('2379.TW','rtw'),('%5ETWII','twii'),
            ('0050.TW','etf50'),('0981.HK','smic'),('005930.KS','samsung'),
            ('JPY%3DX','jpytwd'),('TWD%3DX','twdjpy')]:
    peer(k,l)

# ---- RSS parse with dates ----
def rss(path):
    try: s=open(path,encoding='utf-8',errors='ignore').read()
    except Exception: return []
    items=re.findall(r'<item>(.*?)</item>',s,flags=re.S)
    out=[]
    for it in items:
        t=re.search(r'<title>(.*?)</title>',it,flags=re.S)
        p=re.search(r'<pubDate>(.*?)</pubDate>',it,flags=re.S)
        src=re.search(r'<source[^>]*>(.*?)</source>',it,flags=re.S)
        if t: out.append({'title':t.group(1),'pub':p.group(1) if p else None,'src':src.group(1) if src else None})
    return out
OUT['rss_cds']=rss(os.path.join(D,'rss_cds.xml'))
print(json.dumps(OUT,ensure_ascii=False,indent=1,default=str))
