"""Read the current project and optional timeline. No project is opened or created."""
import argparse
import json

from resolve_api_connection import connect, project_manager


def read_current(manager, expected_name=None):
    project = manager.GetCurrentProject()
    if not project:
        raise RuntimeError("No current project. Open the intended project manually.")
    name, project_id = project.GetName(), project.GetUniqueId()
    if not isinstance(name, str) or not isinstance(project_id, str) or not project_id:
        raise RuntimeError("Project identity is incomplete")
    if expected_name is not None and name != expected_name:
        raise RuntimeError("Current project name does not match --expect-project")
    timeline = project.GetCurrentTimeline()
    count = project.GetTimelineCount()
    if not isinstance(count, int) or isinstance(count, bool) or count < 0:
        raise RuntimeError("Timeline count could not be read")
    result = {
        "project": {"name": name, "id": project_id},
        "timeline_count": count,
        "current_timeline": None,
    }
    if timeline:
        timeline_name = timeline.GetName()
        timeline_id = timeline.GetUniqueId()
        if not timeline_name or not timeline_id:
            raise RuntimeError("Timeline identity is incomplete")
        result["current_timeline"] = {"name": timeline_name, "id": timeline_id}
    current = manager.GetCurrentProject()
    if not current or current.GetUniqueId() != project_id:
        raise RuntimeError("Active project changed during reading. Discard this report and inspect Resolve.")
    # Two identity reads detect some changes; they do not make the snapshot atomic.
    return result


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--expect-project", help="Optional exact name check, not a globally unique identity")
    args = parser.parse_args(argv)
    result = read_current(project_manager(connect()), args.expect_project)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
