#!/usr/bin/env python
"""Seed/sync project import sources (labels, icons, order) to the database.

Usage:
  python -m scripts.seed_project_import_sources
  python -m scripts.seed_project_import_sources --dry-run
  python -m scripts.seed_project_import_sources --list
"""
from __future__ import annotations

import argparse
import asyncio
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


async def run_sync(dry_run: bool = False, list_only: bool = False) -> int:
    from src.core.database import async_session_factory
    from src.domain.projects.import_source_catalog import IMPORT_SOURCE_DEFAULTS
    from src.domain.projects.repository import ProjectImportSourceCatalogRepository

    if list_only:
        for item in IMPORT_SOURCE_DEFAULTS:
            print(
                f"  {item['provider']:14s}"
                f" label={item['label']!r}"
                f" icon={item.get('icon')!r}"
                f" order={item.get('sort_order')}"
            )
        return 0

    if dry_run:
        print("DRY-RUN: no changes will be committed")

    async with async_session_factory() as db:
        repo = ProjectImportSourceCatalogRepository(db)
        await repo.upsert_defaults(IMPORT_SOURCE_DEFAULTS)
        rows = await repo.list_visible()
        for row in rows:
            print(f"  [OK] {row.provider:14s} label={row.label!r} icon={row.icon!r}")
        if not dry_run:
            await db.commit()
        else:
            await db.rollback()

    return 0


def main() -> int:
    parser = argparse.ArgumentParser(description="Seed project import-source catalog")
    parser.add_argument("--dry-run", action="store_true", help="Do not commit changes")
    parser.add_argument("--list", action="store_true", help="List seed defaults and exit")
    args = parser.parse_args()
    return asyncio.run(run_sync(dry_run=args.dry_run, list_only=args.list))


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

