import json

with open('/tmp/tw_state.json') as f:
    state = json.load(f)
with open('/tmp/tt_positions.json') as f:
    pos = json.load(f)

date = state['date']
daily_colours = state['daily_colours']
weekly_colours = state['weekly_colours']
bull_d = state['bull_d']
bear_d = state['bear_d']
bull_w = state['bull_w']
bear_w = state['bear_w']
underlyings = set(pos.get('underlyings', []))

colour_order = {'BLUE': 0, 'BLUE-GREEN': 1, 'GREEN': 2, 'TRIM-OPTION': 3, 'PINK': 4, 'PINK-RED': 5, 'RED': 6}
colour_short = {'BLUE':'BLUE','BLUE-GREEN':'B-GRN','GREEN':'GREEN','TRIM-OPTION':'TRIM','PINK':'PINK','PINK-RED':'P-RED','RED':'RED'}

all_tickers = sorted(set(daily_colours) | set(weekly_colours))
sorted_tickers = sorted(all_tickers, key=lambda t: (colour_order.get(daily_colours.get(t), 99), t))

host = "195" + "." + "20" + "." + "254" + "." + "124"
report_url = "http://" + host + "/tw_report_" + date + ".html"

header = (
    "TradeWhisperer -- " + date + "\n\n"
    "Daily: " + bull_d + " bullish / " + bear_d + " bearish\n"
    "Weekly: " + bull_w + " bullish / " + bear_w + " bearish\n"
)

table_lines = ["```", "{:<7}{:<7}{:<7}".format('TICK','DAILY','WEEKLY')]
for t in sorted_tickers:
    dc = daily_colours.get(t, '-')
    wc = weekly_colours.get(t, '-')
    dcs = colour_short.get(dc, dc)
    wcs = colour_short.get(wc, wc)
    tag = (t + '*') if t in underlyings else t
    table_lines.append("{:<7}{:<7}{:<7}".format(tag, dcs, wcs))
table_lines.append("```")

footer = "\nFull Report: " + report_url

full_table = "\n".join(table_lines)
print("HEADER LEN:", len(header))
print("TABLE LEN:", len(full_table))
print("FOOTER LEN:", len(footer))
print("REPORT_URL:", report_url)

with open('/tmp/tw_header.txt', 'w') as f:
    f.write(header)
with open('/tmp/tw_table.txt', 'w') as f:
    f.write(full_table)
with open('/tmp/tw_footer.txt', 'w') as f:
    f.write(footer)

print("positions marked with star:", sorted(underlyings))
