import json
import datetime
from live_data_adapters import fetch_ai_news, fetch_tech_policy_updates, fetch_listener_questions


def load_show_archive(date):
    with open('show_archive.json', 'r') as f:
        archive = json.load(f)
    return archive.get(date)


def generate_script(segment, host, date, dynamic_data):
    template_path = f"segment_templates/{segment.lower().replace(' ', '_')}.txt"
    try:
        with open(template_path, 'r') as f:
            template = f.read()
        script = template.format(
            host_name=host['name'],
            date=date,
            insert_dynamic_ai_news=dynamic_data.get('ai_news', 'No news available.'),
            dynamic_story=dynamic_data.get('ai_story', ''),
            insert_policy_topic=dynamic_data.get('policy_topic', ''),
            policy_details=dynamic_data.get('policy_details', '')
        )
        return script
    except FileNotFoundError:
        return f"[Template missing for segment: {segment}]"


def main():
    today = datetime.date.today().strftime('%Y-%m-%d')
    show = load_show_archive(today)
    if not show:
        print(f"No show archive entry for {today}.")
        return

    # Fetch live data
    ai_news = fetch_ai_news()
    tech_policy = fetch_tech_policy_updates()
    fetch_listener_questions()

    dynamic_data = {
        'ai_news': "; ".join([n['title'] for n in ai_news]) if ai_news else '',
        'ai_story': ai_news[0]['description'] if ai_news else '',
        'policy_topic': tech_policy[0]['title'] if tech_policy else '',
        'policy_details': tech_policy[0]['description'] if tech_policy else ''
    }

    # Generate scripts for each segment
    scripts = []
    for segment in show['segment_order']:
        for host in show['hosts']:
            script = generate_script(segment, host, today, dynamic_data)
            scripts.append({'segment': segment, 'host': host['name'], 'script': script})

    # (Stub) Save or print scripts
    for s in scripts:
        print(f"\n--- {s['segment']} ({s['host']}) ---\n{s['script']}\n")


if __name__ == "__main__":
    main()
