import json
import subprocess
from pathlib import Path

import pytest

from tests.dashboard_bundle import dashboard


AGENDA_CALENDAR = Path(__file__).parents[1] / "frontend" / "agenda-calendar.js"
INDEX = Path(__file__).parents[1] / "frontend" / "index.html"


def run_node(source: str):
    completed = subprocess.run(["node", "-e", source], capture_output=True, text=True)
    assert completed.returncode == 0, completed.stderr
    return json.loads(completed.stdout)


def test_calendar_snapshot_serializes_ordered_all_day_events_with_stable_identity():
    items = [
        {
            "repository": "stackchain/dashboard",
            "number": 12,
            "title": "Plan, ship; verify\\path\nnext",
            "due_date": "2026-08-19T23:00:00-07:00",
            "url": "https://forge.example/git/stackchain/dashboard/issues/12",
        },
        {
            "repository": "stackchain/api",
            "number": 7,
            "title": "API release",
            "due_date": "2026-08-20",
            "url": "https://forge.example/git/stackchain/api/issues/7",
        },
    ]
    source = f"""
const calendar = require({json.dumps(str(AGENDA_CALENDAR))});
const text = calendar.serializeAgendaCalendar({json.dumps(items)}, {{generatedOn:'20260818'}});
process.stdout.write(JSON.stringify({{text}}));
"""

    text = run_node(source)["text"]
    assert text.startswith("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n")
    assert text.endswith("END:VCALENDAR\r\n")
    assert text.count("BEGIN:VEVENT") == 2
    assert text.index("stackchain/dashboard#12") < text.index("stackchain/api#7")
    assert "UID:issue-12@stackchain-dashboard" in text
    assert "DTSTART;VALUE=DATE:20260819" in text
    assert "SUMMARY:Plan\\, ship\\; verify\\\\path\\nnext" in text
    assert "URL:https://forge.example/git/stackchain/dashboard/issues/12" in text
    assert "DTSTAMP:20260818T000000Z" in text
    assert "\n" not in text.replace("\r\n", "")


def test_calendar_snapshot_folds_utf8_lines_to_rfc_octet_limit_without_splitting_characters():
    item = {
        "repository": "stackchain/dashboard",
        "number": 99,
        "title": "Launch 🚀 " + "é" * 60,
        "due_date": "2026-08-21",
        "url": "https://forge.example/git/stackchain/dashboard/issues/99",
    }
    source = f"""
const calendar = require({json.dumps(str(AGENDA_CALENDAR))});
const text = calendar.serializeAgendaCalendar([{json.dumps(item)}], {{generatedOn:'20260818'}});
process.stdout.write(JSON.stringify({{text}}));
"""

    text = run_node(source)["text"]
    physical_lines = text.split("\r\n")
    assert all(len(line.encode("utf-8")) <= 75 for line in physical_lines)
    assert any(line.startswith(" ") for line in physical_lines)
    unfolded = text.replace("\r\n ", "")
    assert "SUMMARY:Launch 🚀 " + "é" * 60 in unfolded


def test_calendar_snapshot_prefers_native_file_share_and_falls_back_to_one_download():
    source = f"""
const calendar = require({json.dumps(str(AGENDA_CALENDAR))});
class FakeFile {{ constructor(parts, name, options) {{ this.parts=parts; this.name=name; this.type=options.type; }} }}
const shared=[];
const nativeNavigator={{canShare:payload => payload.files[0].name.endsWith('.ics'), share:async payload => shared.push(payload)}};
const clicks=[]; const revoked=[];
const document={{createElement:() => ({{click(){{clicks.push({{download:this.download,href:this.href}})}}}})}};
const urlApi={{createObjectURL:()=>'blob:agenda', revokeObjectURL:value=>revoked.push(value)}};
(async () => {{
  const native = await calendar.deliverCalendarSnapshot({{text:'BEGIN:VCALENDAR', filename:'stackchain-agenda.ics', navigator:nativeNavigator, document, urlApi, FileCtor:FakeFile}});
  const fallback = await calendar.deliverCalendarSnapshot({{text:'BEGIN:VCALENDAR', filename:'stackchain-agenda.ics', navigator:{{}}, document, urlApi, FileCtor:FakeFile}});
  process.stdout.write(JSON.stringify({{native,fallback,shared:shared.length,clicks,revoked}}));
}})();
"""

    assert run_node(source) == {
        "native": "shared",
        "fallback": "downloaded",
        "shared": 1,
        "clicks": [{"download": "stackchain-agenda.ics", "href": "blob:agenda"}],
        "revoked": ["blob:agenda"],
    }


@pytest.mark.anyio
async def test_agenda_export_review_requires_selection_and_exposes_snapshot_privacy_boundary():
    markup = INDEX.read_text()
    source = await dashboard()
    feature_source = source + AGENDA_CALENDAR.read_text()

    assert 'id="open-agenda-export"' in markup
    assert 'id="agenda-export-sheet"' in markup
    assert 'id="agenda-export-items"' in markup
    assert 'id="share-agenda-export"' in markup
    assert "This exports a snapshot" in markup
    assert "agendaMyWork(activeMyWork)" in feature_source
    assert "checkbox.checked" in feature_source
    assert "serializeAgendaCalendar(selected" in feature_source
    assert "deliverCalendarSnapshot" in feature_source
    assert "agenda-export-empty" in feature_source
