"""Read stored source paths on ONE chosen timeline track, without relinking.

A stored File Path is not a guarantee of existence, decoding or active proxy usage.
Optional filesystem probes may block on disconnected network storage.
"""
import argparse
from pathlib import Path
from resolve_api_connection import connect
from resolve_api_media import context, api_list, uid, properties, path_key, ensure_current, output


def source_row(item, check_files=False):
    row = {"timeline_item_id": uid(item), "name": item.GetName()}
    media = item.GetMediaPoolItem()
    if not media:
        return dict(row, status="no_media_pool_item")
    row["media_pool_id"] = uid(media)
    raw = properties(media)
    if "File Path" not in raw:
        return dict(row, status="path_property_missing")
    path = raw["File Path"]
    if not isinstance(path, str):
        return dict(row, status="path_value_unexpected_type")
    if not path:
        return dict(row, status="path_empty")
    row.update(status="stored_path", path=path, filesystem="not_checked")
    if check_files:
        try:
            p = Path(path_key(path))
            # stat distinguishes an absent path from many access/I/O errors.
            import stat
            row["filesystem"] = "regular_file_observed" if stat.S_ISREG(p.stat().st_mode) else "not_regular_file"
        except FileNotFoundError:
            row["filesystem"] = "not_found_at_probe_time"
        except (ValueError, OSError) as exc:
            row.update(filesystem="probe_unavailable", probe_error_type=type(exc).__name__)
    return row


def inspect_track(ctx, kind="video", index=1, limit=100, check_files=False):
    if kind not in ("video", "audio") or type(index) is not int or index < 1 or not 1 <= limit <= 500:
        raise ValueError("Use video/audio, a 1-based track index and limit 1..500")
    count = ctx.timeline.GetTrackCount(kind)
    if type(count) is not int or index > count:
        raise ValueError("Chosen track does not exist")
    items = api_list(ctx.timeline.GetItemListInTrack(kind, index), "Track items")
    rows = []
    for item in items[:limit]:
        try:
            rows.append(source_row(item, check_files))
        except Exception as exc:
            rows.append({"status": "read_error", "error_type": type(exc).__name__})
    ensure_current(ctx)
    return {"status": "track_report", "target": ctx.target, "track_type": kind, "track_index": index,
            "track_item_count": len(items), "truncated": len(items) > limit,
            "item_errors": sum(r["status"] == "read_error" for r in rows), "items": rows}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--track-type", choices=("video", "audio"), default="video")
    parser.add_argument("--track", type=int, default=1)
    parser.add_argument("--limit", type=int, default=100)
    parser.add_argument("--check-files", action="store_true", help="Explicitly probe native filesystem; may block on network storage")
    args = parser.parse_args(argv)
    report = inspect_track(context(connect(), need_timeline=True), args.track_type, args.track, args.limit, args.check_files)
    output(report)
    return 2 if report["item_errors"] or report["truncated"] else 0


if __name__ == "__main__":
    raise SystemExit(main())
