#!/usr/bin/env python3
"""
Extract intraday financial time series data from Google Finance HTML page.
"""

import re
import json
from datetime import datetime
from typing import Optional


def extract_data_callbacks(html_content: str) -> dict:
    """Extract all AF_initDataCallback data blocks from HTML."""
    pattern = r"AF_initDataCallback\(\{key: '(ds:\d+)', hash: '\d+', data:(\[.*?\]), sideChannel"
    matches = re.findall(pattern, html_content)
    return {key: data_str for key, data_str in matches}


def parse_timestamp(ts_array: list) -> Optional[datetime]:
    """Parse Google Finance timestamp array into datetime.

    Format: [year, month, day, hour, minute, second, microsecond, [timezone_offset]]
    """
    try:
        year = ts_array[0]
        month = ts_array[1]
        day = ts_array[2]
        hour = ts_array[3] if ts_array[3] is not None else 0
        minute = ts_array[4] if ts_array[4] is not None else 0
        second = ts_array[5] if ts_array[5] is not None else 0

        return datetime(year, month, day, hour, minute, second)
    except (IndexError, TypeError, ValueError):
        return None


def extract_intraday_data(html_content: str) -> list[dict]:
    """Extract intraday (minute-by-minute) price data from HTML."""
    data_callbacks = extract_data_callbacks(html_content)

    if 'ds:10' not in data_callbacks:
        raise ValueError("No intraday data found in HTML")

    data = json.loads(data_callbacks['ds:10'])

    # Navigate to the time series data
    symbol_info = data[0][0]
    time_series_container = symbol_info[3][0]
    data_points = time_series_container[1]

    results = []
    for point in data_points:
        timestamp_arr = point[0]
        values = point[1]

        ts = parse_timestamp(timestamp_arr)
        if ts and values:
            results.append({
                'datetime': ts,
                'price': values[0],
            })

    return results
    