from __future__ import annotations

from pathlib import Path

import pytest

from sync_state_machine.common.persistence import PersistenceBackend
from sync_state_machine.pipeline import run_profile_from_file
from sync_state_machine.pipeline.full_sync_pipeline import FullSyncPipeline


def _write_yaml(path: Path, content: str) -> None:
    path.write_text(content.strip() + "\n", encoding="utf-8")


@pytest.mark.asyncio
async def test_multi_project_pipeline_runs_jsonl_to_jsonl_with_shared_persistence(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    pytest.importorskip("yaml")

    async def _skip_post_check(self) -> bool:
        return True

    monkeypatch.setattr(FullSyncPipeline, "phase_post_check", _skip_post_check)

    project_root = Path(__file__).resolve().parents[2]
    local_dir = project_root / "working_local_datasource" / "20260302-020003"
    remote_dir = tmp_path / "remote_jsonl"
    db_path = tmp_path / "multi_project.db"
    logs_dir = tmp_path / "logs"
    remote_dir.mkdir(parents=True, exist_ok=True)
    logs_dir.mkdir(parents=True, exist_ok=True)

    global_cfg = tmp_path / "global.yaml"
    project_cfg = tmp_path / "project.yaml"
    multi_cfg = tmp_path / "multi.yaml"

    _write_yaml(
        global_cfg,
        f"""
node_types:
  - project
local_datasource:
  type: jsonl
  jsonl_dir: {local_dir.as_posix()}
  read_only: false
remote_datasource:
  type: jsonl
  jsonl_dir: {remote_dir.as_posix()}
  read_only: false
persist:
  backend: sqlite
  db_path: {db_path.as_posix()}
  enable: true
  wipe_on_start: true
logging:
  initialize: true
  file_dir: {logs_dir.as_posix()}
  file_name_pattern: multi_global_{{timestamp}}.log
  level: 20
strategies:
  project:
    skip_sync: false
    config:
      auto_bind: true
      auto_bind_fields:
        - name
      depend_fields: {{}}
      local_orphan_action: create_remote
      remote_orphan_action: none
      update_direction: push
        """,
    )

    _write_yaml(
        project_cfg,
        f"""
node_types:
  - lar
local_datasource:
  type: jsonl
  jsonl_dir: {local_dir.as_posix()}
  read_only: false
remote_datasource:
  type: jsonl
  jsonl_dir: {remote_dir.as_posix()}
  read_only: false
persist:
  backend: sqlite
  db_path: {db_path.as_posix()}
  enable: true
  wipe_on_start: false
logging:
  initialize: true
  file_dir: {logs_dir.as_posix()}
  file_name_pattern: multi_project_{{timestamp}}.log
  level: 20
strategies:
  lar:
    skip_sync: false
    config:
      auto_bind: true
      auto_bind_fields:
        - project_id
      depend_fields:
        project_id: project
      local_orphan_action: create_remote
      remote_orphan_action: none
      update_direction: push
        """,
    )

    _write_yaml(
        multi_cfg,
        f"""
global_config: {global_cfg.as_posix()}
default_project_config: {project_cfg.as_posix()}
projects:
  - local_project_id: f3e02e84-e81c-4aa6-88d4-f5aa108c8227
    remote_project_id: f3e02e84-e81c-4aa6-88d4-f5aa108c8227
  - local_project_id: 0f9c3e22-f4bb-4803-825a-4f238eeb06d5
    remote_project_id: 0f9c3e22-f4bb-4803-825a-4f238eeb06d5
        """,
    )

    results = await run_profile_from_file(project_root=project_root, config_path=multi_cfg, print_summary=False)

    assert "global" in results
    assert "project_id:f3e02e84-e81c-4aa6-88d4-f5aa108c8227" in results
    assert "project_id:0f9c3e22-f4bb-4803-825a-4f238eeb06d5" in results

    _, scope_rows = PersistenceBackend.query_records(
        backend="sqlite",
        db_path=str(db_path),
        sql="SELECT DISTINCT scope FROM nodes ORDER BY scope",
    )
    scopes = [row["scope"] for row in scope_rows]
    assert scopes == [
        "global",
        "project_id:0f9c3e22-f4bb-4803-825a-4f238eeb06d5",
        "project_id:f3e02e84-e81c-4aa6-88d4-f5aa108c8227",
    ]

    _, copied_rows = PersistenceBackend.query_records(
        backend="sqlite",
        db_path=str(db_path),
        sql=(
        "SELECT scope, collection_id, node_type, COUNT(1) AS c "
            "FROM nodes "
        "WHERE scope <> 'global' AND node_type = 'project' "
            "GROUP BY scope, collection_id, node_type "
            "ORDER BY scope, collection_id, node_type"
        ),
    )
    assert copied_rows == []