"""Contract tests for the JSON-file-backed runtime storage:
InvestmentManager/routes/alerts_system.py, knowledge_center.py,
agent_panel_scheduler.py and lead_hunter_seekers.py.

Each module resolves its storage location on every call through a small
resolver function (_alerts_folder(), _notes_path(), _notifications_path(),
_backup_folder(), _schedules_folder(), _schedules_backup_folder(),
_leads_path()) backed by modules/core/storage_paths.py, so DATA_DIR loaded
from .env is honoured. The tests below monkeypatch those resolvers to point
at tmp_path.

Importing these modules performs no filesystem work: folders and JSON files
are created on first write, and readers treat a missing file as empty. That
import-time contract is checked in a throwaway subprocess, because
re-importing route modules in-process would re-register their Flask routes
on the shared blueprint.
"""
import json
import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]


# ---------------------------------------------------------------------------
# alerts_system.py
# ---------------------------------------------------------------------------

class TestAlertsJsonStorage:
    def test_load_alerts_returns_empty_list_when_file_missing(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.alerts_system as alerts_module

        monkeypatch.setattr(alerts_module, "_alerts_folder", lambda: str(tmp_path))
        assert alerts_module.load_alerts(9001) == []

    def test_push_alert_creates_user_file_and_prepends_newest_first(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.alerts_system as alerts_module

        monkeypatch.setattr(alerts_module, "_alerts_folder", lambda: str(tmp_path))
        alerts_module.push_alert(9002, "Pierwszy alert")
        alerts_module.push_alert(9002, "Drugi alert")

        alert_file = tmp_path / "9002.json"
        assert alert_file.is_file()
        data = json.loads(alert_file.read_text(encoding="utf-8"))
        assert [a["message"] for a in data] == ["Drugi alert", "Pierwszy alert"]
        assert data[0]["read"] is False

    def test_load_alerts_fails_closed_on_corrupt_json(self, tmp_path, monkeypatch):
        """S2 (approved): a damaged store is NOT an empty list any more (the next save used to wipe it); the file is kept."""
        import pytest
        from modules.core.json_store import JsonStoreCorrupt
        import InvestmentManager.routes.alerts_system as alerts_module

        monkeypatch.setattr(alerts_module, "_alerts_folder", lambda: str(tmp_path))
        (tmp_path / "9003.json").write_text("{not valid json", encoding="utf-8")
        with pytest.raises(JsonStoreCorrupt):
            alerts_module.load_alerts(9003)
        with pytest.raises(JsonStoreCorrupt):
            alerts_module.push_alert(9003, "must not overwrite")
        assert (tmp_path / "9003.json").read_text(encoding="utf-8") == "{not valid json"

    def test_alerts_are_isolated_per_user_id(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.alerts_system as alerts_module

        monkeypatch.setattr(alerts_module, "_alerts_folder", lambda: str(tmp_path))
        alerts_module.push_alert(9004, "Dla usera 9004")
        alerts_module.push_alert(9005, "Dla usera 9005")

        assert len(alerts_module.load_alerts(9004)) == 1
        assert len(alerts_module.load_alerts(9005)) == 1
        assert alerts_module.load_alerts(9004)[0]["message"] == "Dla usera 9004"


# ---------------------------------------------------------------------------
# knowledge_center.py: notes.json, notifications.json, backups
# ---------------------------------------------------------------------------

class TestKnowledgeCenterNotesStorage:
    def test_load_notes_empty_when_file_absent(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        monkeypatch.setattr(kc, "_notes_path", lambda: str(tmp_path / "all_notes.json"))
        assert kc.load_notes() == []

    def test_save_then_load_notes_round_trips(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        notes_path = tmp_path / "all_notes.json"
        monkeypatch.setattr(kc, "_notes_path", lambda: str(notes_path))
        kc.save_notes([{"title": "T", "content": "C"}])
        assert kc.load_notes() == [{"title": "T", "content": "C"}]

    def test_notifications_round_trip(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        notif_path = tmp_path / "notifications.json"
        monkeypatch.setattr(kc, "_notifications_path", lambda: str(notif_path))
        kc.save_notifications([{"user_id": 1, "read": False}])
        assert kc.load_notifications() == [{"user_id": 1, "read": False}]

    def test_backup_notes_is_a_noop_when_no_notes_file(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        monkeypatch.setattr(kc, "_notes_path", lambda: str(tmp_path / "all_notes.json"))
        monkeypatch.setattr(kc, "_backup_folder", lambda: str(tmp_path / "backups"))
        kc.backup_notes()  # must not raise, and must not create the backups folder
        assert not (tmp_path / "backups").exists()

    def test_backup_notes_copies_current_content(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        notes_path = tmp_path / "all_notes.json"
        backup_dir = tmp_path / "backups"
        backup_dir.mkdir()
        notes_path.write_text('[{"title": "x"}]', encoding="utf-8")

        monkeypatch.setattr(kc, "_notes_path", lambda: str(notes_path))
        monkeypatch.setattr(kc, "_backup_folder", lambda: str(backup_dir))
        kc.backup_notes()

        backups = list(backup_dir.glob("all_notes_backup_*.json"))
        assert len(backups) == 1
        assert backups[0].read_text(encoding="utf-8") == '[{"title": "x"}]'

    def test_backup_notes_keeps_only_10_newest(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.knowledge_center as kc

        notes_path = tmp_path / "all_notes.json"
        backup_dir = tmp_path / "backups"
        backup_dir.mkdir()
        notes_path.write_text("[]", encoding="utf-8")
        monkeypatch.setattr(kc, "_notes_path", lambda: str(notes_path))
        monkeypatch.setattr(kc, "_backup_folder", lambda: str(backup_dir))

        # Pre-seed 12 backups with names that sort deterministically.
        for i in range(12):
            (backup_dir / f"all_notes_backup_2026010{i:02d}_000000.json").write_text("[]")

        kc.backup_notes()  # creates a 13th, then trims to 10 newest by name-sort

        remaining = list(backup_dir.glob("all_notes_backup_*.json"))
        assert len(remaining) == 10


# ---------------------------------------------------------------------------
# agent_panel_scheduler.py: schedules + their backups
# ---------------------------------------------------------------------------

class TestAgentScheduleBackupStorage:
    def test_backup_schedule_is_a_noop_when_no_schedule_file(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.agent_panel_scheduler as scheduler

        monkeypatch.setattr(scheduler, "_schedules_folder", lambda: str(tmp_path))
        monkeypatch.setattr(scheduler, "_schedules_backup_folder", lambda: str(tmp_path / "backups"))
        scheduler.backup_schedule(9101)  # must not raise

    def test_backup_schedule_copies_into_per_user_subfolder(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.agent_panel_scheduler as scheduler

        schedules_dir = tmp_path / "schedules"
        schedules_dir.mkdir()
        backups_dir = tmp_path / "schedules" / "backups"
        (schedules_dir / "9102.json").write_text('[{"title": "spotkanie"}]', encoding="utf-8")

        monkeypatch.setattr(scheduler, "_schedules_folder", lambda: str(schedules_dir))
        monkeypatch.setattr(scheduler, "_schedules_backup_folder", lambda: str(backups_dir))

        scheduler.backup_schedule(9102)

        user_backup_dir = backups_dir / "9102"
        assert user_backup_dir.is_dir()
        backups = list(user_backup_dir.glob("backup_*.json"))
        assert len(backups) == 1
        assert backups[0].read_text(encoding="utf-8") == '[{"title": "spotkanie"}]'

    def test_backup_schedule_keeps_only_5_newest_per_user(self, tmp_path, monkeypatch):
        import InvestmentManager.routes.agent_panel_scheduler as scheduler

        schedules_dir = tmp_path / "schedules"
        schedules_dir.mkdir()
        backups_dir = tmp_path / "schedules" / "backups"
        user_backup_dir = backups_dir / "9103"
        user_backup_dir.mkdir(parents=True)
        (schedules_dir / "9103.json").write_text("[]", encoding="utf-8")

        for i in range(7):
            (user_backup_dir / f"backup_2026010{i}_0000.json").write_text("[]")

        monkeypatch.setattr(scheduler, "_schedules_folder", lambda: str(schedules_dir))
        monkeypatch.setattr(scheduler, "_schedules_backup_folder", lambda: str(backups_dir))

        scheduler.backup_schedule(9103)  # adds an 8th, then trims to 5 newest by name-sort

        remaining = list(user_backup_dir.glob("backup_*.json"))
        assert len(remaining) == 5


# ---------------------------------------------------------------------------
# Import-time contract: importing the CRM JSON-storage modules creates
# nothing; the first write creates the storage lazily. Runs in an isolated
# subprocess (see the module docstring for why in-process reload is unsafe).
# ---------------------------------------------------------------------------

_IMPORT_PROBE_SCRIPT = '''import os, sys, json
from pathlib import Path

sys.path.insert(0, {repo_root!r})
os.environ["FLASK_ENV"] = "development"
os.environ["SECRET_KEY"] = "test"
os.environ.pop("DATA_DIR", None)

# Point the central resolver at a throwaway fake repo root so even a
# regression could only ever write inside it.
from modules.core import storage_paths
storage_paths.REPO_ROOT = Path({fake_repo_root!r})

import InvestmentManager.routes.alerts_system as alerts
import InvestmentManager.routes.knowledge_center as kc
import InvestmentManager.routes.agent_panel_scheduler as scheduler
import InvestmentManager.routes.lead_hunter_seekers as seekers

def tree():
    root = Path({fake_repo_root!r})
    return sorted(str(p.relative_to(root)).replace(os.sep, "/") for p in root.rglob("*"))

after_import = tree()
reads = [alerts.load_alerts(1), kc.load_notes(), kc.load_notifications(), seekers.load_leads()]
after_reads = tree()

kc.save_notes([])
kc.save_notifications([])
seekers.save_leads([])
alerts.save_alerts(1, [])

print(json.dumps({{
    "after_import": after_import,
    "reads": reads,
    "after_reads": after_reads,
    "after_writes": tree(),
    "notes_path_under_fake_root": kc._notes_path().startswith({fake_repo_root!r}),
}}))
'''


def test_importing_crm_json_modules_creates_nothing_and_first_write_creates_storage(tmp_path):
    import tempfile

    script_path = tmp_path / "probe_crm_json_imports.py"

    with tempfile.TemporaryDirectory() as fresh_cwd, tempfile.TemporaryDirectory() as fake_repo_root:
        script_path.write_text(
            _IMPORT_PROBE_SCRIPT.format(
                repo_root=str(REPO_ROOT), fake_repo_root=fake_repo_root
            ),
            encoding="utf-8",
        )
        result = subprocess.run(
            [sys.executable, str(script_path)],
            cwd=fresh_cwd,
            capture_output=True,
            text=True,
            timeout=60,
        )

    assert result.returncode == 0, result.stderr
    payload = json.loads(result.stdout.strip().splitlines()[-1])
    assert payload["after_import"] == []
    assert payload["reads"] == [[], [], [], []]
    assert payload["after_reads"] == []
    assert payload["notes_path_under_fake_root"] is True
    for created in (
        "InvestmentManager/alerts/1.json",
        "InvestmentManager/knowledge_center/all_notes.json",
        "InvestmentManager/knowledge_center/notifications.json",
        "InvestmentManager/knowledge_center/manual_leads.json",
    ):
        assert created in payload["after_writes"], created
