"""Main module for speech_to_text package.

This is a refactor of the previous root `main.py` logic. It exposes a
`main()` function suitable to be used as a console script entry point.
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from pathlib import Path
import time


def _build_driver():
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--use-fake-ui-for-media-stream")
    # If you need a headless run with fake audio, add the appropriate flags
    # chrome_options.add_argument("--use-fake-device-for-media-stream")
    # chrome_options.add_argument("--use-file-for-fake-audio-capture=/path/to/file.wav")

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
    return driver


def listen(driver=None, poll_interval=0.5, max_run_seconds=300, index_path=None, out_path=None):
    """Start the browser (if needed), click the Start button and poll `#result`.

    Parameters
    - driver: optional selenium webdriver instance. If None, a new one is created.
    - poll_interval: seconds between polls for transcript updates.
    - max_run_seconds: maximum seconds to run before stopping.
    - index_path: optional Path to index.html (defaults to project root index.html).
    - out_path: optional Path to write transcript (defaults to input.txt in project dir).

    Returns the last captured transcript (string) or empty string.
    """
    own_driver = False
    if driver is None:
        driver = _build_driver()
        own_driver = True

    project_dir = Path(__file__).resolve().parent.parent
    if index_path is None:
        index_path = project_dir / "index.html"
    if not Path(index_path).exists():
        raise FileNotFoundError(f"index.html not found at {index_path}")

    website = Path(index_path).resolve().as_uri()
    driver.get(website)

    if out_path is None:
        out_path = project_dir / "input.txt"

    output_text = ""
    try:
        start_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, "start-btn"))
        )
        start_btn.click()
        print("Clicked Start — Listening... Allow microphone access in the browser.")

        start_time = time.time()

        while True:
            if time.time() - start_time > max_run_seconds:
                print("Max run time reached — stopping.")
                break

            output_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "result"))
            )
            current_text = output_element.text.strip()

            if current_text and current_text != output_text:
                output_text = current_text
                print(f"Transcription: {output_text}")
                Path(out_path).write_text(output_text.lower(), encoding="utf-8")

            time.sleep(poll_interval)

    except KeyboardInterrupt:
        print("Stopped listening (KeyboardInterrupt).")
    except Exception as e:
        print("An error occurred:", str(e))
    finally:
        if own_driver:
            try:
                driver.quit()
            except Exception:
                pass

    return output_text


def main():
    listen()


if __name__ == "__main__":
    main()
