import os
import sys
from ..database import SessionLocal
from ..models.stream import Stream
from ..config import settings


def _build_hls_url(hls_path: str) -> str:
    """Build consistent HLS URL from path."""
    if not hls_path:
        return None

    url_path = hls_path.replace(settings.FFMPEG_CACHE_PATH, "/hls")
    if not url_path.endswith('.m3u8'):
        url_path = f"{url_path.rstrip('/')}/index.m3u8"

    if not url_path.startswith('http'):
        url_path = f"https://{settings.DOMAIN}{url_path}" if settings.DOMAIN else url_path

    return url_path


def regenerate_master_ffconcat():
    """Regenerate the master.ffconcat file from all ready streams."""
    try:
        db = SessionLocal()
        try:
            streams = db.query(Stream).filter(
                Stream.status == 'ready',
                Stream.hls_path.isnot(None)
            ).order_by(Stream.stream_date.desc(), Stream.created_at.desc()).all()

            lines = ['ffconcat version 1.0']
            for stream in streams:
                hls_url = _build_hls_url(stream.hls_path)
                if hls_url:
                    lines.append(f"file '{hls_url}'")

            content = '\n'.join(lines)
            output_path = os.path.join(settings.UPLOAD_PATH, 'master.ffconcat')
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            with open(output_path, 'w') as f:
                f.write(content)

            sys.stderr.write(f"[FFCONCAT] Regenerated master.ffconcat with {len(streams)} streams at {output_path}\n")
            sys.stderr.flush()
        finally:
            db.close()
    except Exception as e:
        sys.stderr.write(f"[FFCONCAT ERROR] Failed to regenerate: {e}\n")
        sys.stderr.flush()
