import asyncio, os
import simplematrixbotlib as botlib
import feedparser
from typing_extensions import TypedDict
from liquid import Template
import aiohttp
from utils import validate_config, bot_factory, feedMeta, process_new_objects
import json
import tracemalloc
import linecache
from prometheus_client import start_http_server, Summary, Counter, Gauge
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s || %(levelname)s || %(name)s.%(funcName)s:%(lineno)d || %(message)s')

persistedMetadata = feedMeta(etag=None, modified=None)
promMatrixSentCounter = Counter('matrix_rss_bridge_articles_sent', 'Number of RSS articles sent to matrix', ['room_id', 'source_name'])
promMatrixFunkyLoopCount = Gauge('matrix_rss_bridge_funky_loop', 'number of times the app looped. i need to fix this crap', ['source_name'])
promMatrixParsedNewRecords = Gauge('matrix_rss_bridge_parsed_new_records', 'number of records returned by feedparser', ['source_name'])
promMatrixParsedOldRecords = Gauge('matrix_rss_bridge_parsed_old_records', 'number of records in local json file', ['source_name'])
promMatrixLastCheckEpoch = Gauge('matrix_rss_bridge_last_check', 'Epoch of the last time the loop checked the source',[ 'source_name'])
promMatrixLastCheckEpoch_target = Gauge('matrix_rss_bridge_last_check_target_seconds', 'How often do we expect the RSS check to finish')
promMatrixLastCheckDuration = Summary('matrix_rss_bridge_last_check_duration_seconds', 'How many seconds did the RSS source polling take',[ 'source_name' ])

def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    logging.info("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        logging.info("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            logging.info('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        logging.info("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    logging.info("Total allocated size: %.1f KiB" % (total / 1024))

async def loop(bot, interval, feed_path, bridges, message_template, ff_tracemalloc):
  async def check_feed(session, feed_path, bridge, message_template,ff_tracemalloc):
    with promMatrixLastCheckDuration.labels(source_name="check_feed").time():
      name, url, room_id = bridge['name'], bridge['feed_url'], bridge['room_id']
      json_file_path = f'{feed_path}/{name}.json'
      logging.info(f'checking feed: {url}')
      logging.debug(f'Loading metadata from: {json_file_path}')
      message_template = dict.get(bridge, 'template_markdown', message_template)
      template = Template(message_template)
      promMatrixParsedNewRecords.labels(source_name=name).set(0)
      promMatrixParsedOldRecords.labels(source_name=name).set(0)
      emptyMeta = feedMeta(etag=None, modified=None)
      if not os.path.isfile(json_file_path):
        with open(json_file_path, 'w', encoding='utf-8') as f:
          json.dump(emptyMeta, f, ensure_ascii=False, indent=4)

      with open(json_file_path, 'r') as json_file:
        persistedMetadata = json.loads(json_file.read())
      new_parsed = feedparser.parse(url, etag=persistedMetadata['etag'], modified=persistedMetadata['modified'])
      logging.debug(new_parsed)
      promMatrixLastCheckEpoch.labels(source_name=name).set_to_current_time()
    
      if hasattr(new_parsed, 'etag'):
        if new_parsed.etag is not None:
          persistedMetadata['etag'] = new_parsed.etag
      if hasattr(new_parsed, 'modified'):
        if new_parsed.modified is not None:
          persistedMetadata['modified'] = new_parsed.modified


      with open(json_file_path, 'w', encoding='utf-8') as f:
        json.dump(persistedMetadata, f, ensure_ascii=False, indent=4)
      newRecordsToSend = []
      allRecords = new_parsed.entries
      
      
      if not os.path.isfile(f'{feed_path}/{name}_entries.json'):
        logging.info('There is no existing entries file, starting with all the records')
        newRecordsToSend = new_parsed.entries
      else:
        logging.debug('Entries file exists, only sending the latest entries')
        with open(f'{feed_path}/{name}_entries.json') as f:
          old_parsed = json.loads(f.read())
          logging.debug(f'there are {len(new_parsed.entries)} new entries for {url}')
          promMatrixParsedNewRecords.labels(source_name=name).set(len(new_parsed.entries))
          logging.debug(f'there are {len(old_parsed)} old entries for {url}')
          promMatrixParsedOldRecords.labels(source_name=name).set(len(old_parsed))
          i = 0
          with promMatrixLastCheckDuration.labels(source_name="process_new_objects").time():
            entries = process_new_objects(new_parsed.entries,old_parsed)
          for e in entries:
            newRecordsToSend.append(e)
      
      if len(newRecordsToSend) > 0:
        logging.info(f'sending {len(newRecordsToSend)} entries')
        logging.info(f'dumping all {len(allRecords)} entries to json file')
        with open(f'{feed_path}/{name}_entries.json', 'w', encoding='utf-8') as f:
            json.dump(allRecords, f, ensure_ascii=False, indent=4)
        messageTruncationLength = 1000
        for entry in newRecordsToSend:
          message = template.render(**entry)
          if len(message) > messageTruncationLength:
            message = message[0:messageTruncationLength] + "..."
          logging.debug(f'sending message {message} to room {room_id}')
          promMatrixSentCounter.labels(room_id=room_id, source_name=name).inc()
          await bot.api.send_markdown_message(room_id, message)
        logging.info("done sending this feed's entries")
    

  while True:
    await asyncio.sleep(0.01+interval)
    if ff_tracemalloc:
      snapshot = tracemalloc.take_snapshot()
      display_top(snapshot)
    async with aiohttp.ClientSession() as session:
      await asyncio.gather(*tuple([check_feed(session, feed_path, bridge, message_template,ff_tracemalloc) for bridge in bridges]))
def f(bridges):
  outVar = ''
  for bridge in bridges:
    outVar += bridge['name']
  return outVar
def main():
  config = validate_config("config.toml")
  if not os.path.isdir(config['feed_path'] if 'feed_path' in config else '.feeds'):
    os.mkdir(config['feed_path'])
  
  # Set up prometheus metrics here before the web server on the configured port is started
  promMatrixLastCheckEpoch_target.set(config['interval'])
  # promMatrixLastCheckEpoch.set_to_current_time()
  logging.info(f"f: {f(config['bridge'])}")
  if config['ff_tracemalloc']:
      tracemalloc.start()
  start_http_server(config['prometheus_port'])

  creds = botlib.Creds(
    config['homeserver'],
    config['username'],
    config['password'] if 'password' in config else None,
    config['login_token'] if 'login_token' in config else None,
    config['access_token'] if 'access_token' in config else None
  )
  logging.info("Starting the bot factory up")
  bot = bot_factory(
    creds, loop, [
      config['interval'], config['feed_path'], config['bridge'], config['message_template'] if 'message_template' in config else '<h1>{{title}}</h1>\n\n{{published}} at {{link}}\n{{summary}}', config['ff_tracemalloc']
      ]
    )
  logging.info('running bot')
  bot.run()

if __name__ == '__main__':
    main()
