#!/usr/bin/env python3
"""Create a source-linked Markdown transcript from an authorized local recording."""
import argparse
from datetime import datetime, timezone
from pathlib import Path


def timestamp(seconds):
    value = int(seconds)
    return f"{value // 3600:02d}:{value // 60 % 60:02d}:{value % 60:02d}"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("audio", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--title", required=True)
    parser.add_argument("--source", required=True)
    args = parser.parse_args()
    if not args.audio.is_file():
        parser.error("Audio file does not exist")
    if args.output.exists():
        parser.error("Output exists; choose a new file")
    if not args.title.strip() or not args.source.strip() or any("\n" in value or "\r" in value for value in [args.title, args.source]):
        parser.error("Title and source must be nonempty single-line values")
    from faster_whisper import WhisperModel
    model = WhisperModel("small", device="cpu", compute_type="int8")
    segments, info = model.transcribe(str(args.audio), vad_filter=True)
    lines = [f"# {args.title}", "", f"Source: {args.source}", f"Captured: {datetime.now(timezone.utc).isoformat()}",
             "Method: local faster-whisper small, CPU int8", f"Detected language: {info.language}", "", "## Transcript", ""]
    count = 0
    for segment in segments:
        if segment.text.strip():
            count += 1
            lines.append(f"[{timestamp(segment.start)} - {timestamp(segment.end)}] {segment.text.strip()}")
            if count > 20000:
                raise ValueError("Too many segments for this learning build")
    if count == 0:
        parser.error("No speech segments; no note was created")
    with args.output.open("x", encoding="utf-8") as handle:
        handle.write("\n\n".join(lines) + "\n")
    print(f"Saved {count} segments to {args.output}; check names, numbers, and timestamps against the recording.")


if __name__ == "__main__":
    main()
