import argparse
import csv
import re
from pathlib import Path

# Matches [HH:MM:SS.mmm --&gt; HH:MM:SS.mmm] or [HH:MM:SS.mmm --> HH:MM:SS.mmm]
TIMESTAMP_RE = re.compile(
    r'\[(\d{1,2}):(\d{2}):(\d{2})(?:\.\d{1,3})?\s*(?:--&gt;|-->)\s*\d{1,2}:\d{2}:\d{2}(?:\.\d{1,3})?\](?!</a>)'
)


def add_timestamp_links(html_content: str, mp3_url: str) -> tuple[str, int]:
    # Clean up accidental whitespace/quotes and encode spaces if present
    clean_url = mp3_url.strip().strip('"').strip("'").replace(" ", "%20")

    def replace_match(match: re.Match) -> str:
        hours = int(match.group(1))
        minutes = int(match.group(2))
        seconds = int(match.group(3))

        total_seconds = hours * 3600 + minutes * 60 + seconds
        original_text = match.group(0)

        return (
            f'<a href="{clean_url}#t={total_seconds}" '
            f'target="_blank" rel="noopener">{original_text}</a>'
        )

    return TIMESTAMP_RE.subn(replace_match, html_content)


def process_file(html_path: Path, mp3_url: str, output_dir: Path) -> None:
    if not html_path.is_file():
        print(f"Skipped (file not found): {html_path}")
        return

    try:
        content = html_path.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        content = html_path.read_text(encoding="latin-1")

    updated_content, count = add_timestamp_links(content, mp3_url)

    output_dir.mkdir(parents=True, exist_ok=True)
    out_path = output_dir / html_path.name
    out_path.write_text(updated_content, encoding="utf-8")

    print(f"Done: {html_path.name} -> {out_path} ({count} timestamps linked)")


def main():
    parser = argparse.ArgumentParser(
        description="Link HTML transcript timestamps to remote MP3 files."
    )
    parser.add_argument("html_file", nargs="?", help="Path to a single HTML file")
    parser.add_argument("mp3_url", nargs="?", help="Full URL to the corresponding MP3")
    parser.add_argument(
        "-d", "--dir", default="./html_files",
        help="Input folder for interactive/CSV mode (default: ./html_files)"
    )
    parser.add_argument(
        "-o", "--output", default="./linked_html",
        help="Output folder for updated HTML files (default: ./linked_html)"
    )
    parser.add_argument(
        "--csv", help="CSV file mapping HTML filenames to MP3 URLs (filename,url)"
    )

    args = parser.parse_args()
    output_dir = Path(args.output)

    # Mode 1: Batch processing via CSV file
    if args.csv:
        csv_path = Path(args.csv)
        base_dir = Path(args.dir)
        with csv_path.open(newline="", encoding="utf-8-sig") as f:
            reader = csv.reader(f)
            for row_idx, row in enumerate(reader):
                if len(row) < 2 or not row[0].strip() or not row[1].strip():
                    continue
                file_entry, mp3_url = row[0].strip(), row[1].strip()
                # Skip header row if present
                if row_idx == 0 and not mp3_url.lower().startswith(("http://", "https://")):
                    continue
                html_path = Path(file_entry)
                if not html_path.exists():
                    html_path = base_dir / file_entry
                process_file(html_path, mp3_url, output_dir)
        return

    # Mode 2: Single HTML file passed as an argument
    if args.html_file:
        html_path = Path(args.html_file)
        mp3_url = args.mp3_url or input(f"Enter MP3 URL for {html_path.name}: ").strip()
        if mp3_url:
            process_file(html_path, mp3_url, output_dir)
        else:
            print("No URL provided. Cancelled.")
        return

    # Mode 3: Interactive folder mode
    input_dir = Path(args.dir)
    if not input_dir.exists():
        folder_input = input(
            f"Folder '{input_dir}' not found. Enter path to HTML folder: "
        ).strip().strip('"').strip("'")
        input_dir = Path(folder_input)

    html_files = sorted(list(input_dir.glob("*.html")) + list(input_dir.glob("*.htm")))
    if not html_files:
        print(f"No HTML files found in '{input_dir}'.")
        return

    print(f"Found {len(html_files)} HTML file(s) in '{input_dir}'.")
    for html_path in html_files:
        mp3_url = input(
            f"\n[{html_path.name}] Paste MP3 URL (or press Enter to skip): "
        ).strip()
        if mp3_url:
            process_file(html_path, mp3_url, output_dir)
        else:
            print(f"Skipped {html_path.name}.")


if __name__ == "__main__":
    main()
