from pathlib import Path

from fastapi.testclient import TestClient
from sqlmodel import Session, select

from app.core.config import get_settings
from app.db.session import init_db, reset_db_for_tests
from app.main import app
from app.models.core import PostDraft, Provider, UploadRequest, VideoAsset, WebsiteCompanion
from app.services.upload_requests import complete_request


def setup_test_db(tmp_path):
    settings = get_settings()
    settings.database_url = "sqlite://"
    settings.storage_root = tmp_path / "storage"
    engine = init_db(settings)
    reset_db_for_tests(engine)
    return engine, TestClient(app)


def test_private_youtube_completion_prepares_website_companion_without_public_link(tmp_path):
    engine, client = setup_test_db(tmp_path)
    video_path = tmp_path / "video.mp4"
    video_path.write_bytes(b"video")
    with Session(engine) as session:
        video = VideoAsset(candidate_id="pkg-private-site", package_id="pkg-private-site", file_path=str(video_path), checksum="abc", working_title="Private Site", status="uploaded_private")
        session.add(video); session.commit(); session.refresh(video)
        draft = PostDraft(video_asset_id=video.id, provider=Provider.youtube, title="Private Site", description="Safe guide", tags_json=["#scamalert"], privacy_status="private")
        session.add(draft); session.commit(); session.refresh(draft)
        req = UploadRequest(video_asset_id=video.id, post_draft_id=draft.id, status="sent_to_executor", expected_video_sha="abc", metadata_snapshot_json={"description": "Safe guide"})
        session.add(req); session.commit(); session.refresh(req)
        complete_request(session, req.id, {"youtube_video_id": "PRIVATE123"})
        comp = session.exec(select(WebsiteCompanion).where(WebsiteCompanion.video_asset_id == video.id)).first()
        assert comp.status == "ready_without_public_video"
        assert comp.video_url_internal == "https://www.youtube.com/shorts/PRIVATE123"
        assert comp.website_link_allowed is False
        video_id = video.id
    payload = client.post(f"/api/website/companions/{video_id}/prepare-payload").json()["payload"]
    assert payload["videoUrl"] is None
    assert payload["source"]["youtube_video_id"] == "PRIVATE123"
    assert payload["source"]["website_link_allowed"] is False
    assert payload["source"]["public_video_url_visible"] is False


def test_full_idea_to_private_upload_to_website_payload_workflow(tmp_path):
    _, client = setup_test_db(tmp_path)
    created = client.post("/api/production-queue", json={
        "title": "Refund link that steals the card",
        "brief": "Open on a fake refund screen, call out that refunds should not need the full card again, then show the safer move.",
        "status": "locked_next",
        "source": "manual",
    }).json()
    concept = client.post(f"/api/agent/production/{created['id']}/concept-proposed").json()["concept"]
    assert concept["confirm_command"] == f"APPROVE_PRODUCTION {created['id']}"
    client.post(f"/api/agent/production/{created['id']}/approve-generation", json={"approval_source": "pytest"})
    package = client.post(f"/api/agent/production/{created['id']}/generate-review-package").json()
    assert package["ok"] is True
    video_id = package["video_asset_id"]
    video = client.get(f"/api/videos/{video_id}").json()
    youtube_draft = next(d for d in video["drafts"] if d["provider"] == "youtube")
    snapshot = client.get(f"/api/upload-requests/youtube-private/{youtube_draft['id']}/snapshot").json()["upload_snapshot"]
    assert snapshot["privacy_status"] == "private"
    assert snapshot["sha_prefix"]
    upload_request = client.post(f"/api/upload-requests/youtube-private/{youtube_draft['id']}/save-and-approve", json={"approved_by": "pytest"}).json()
    assert upload_request["status"] == "approved"
    assert "APPROVE_UPLOAD" in upload_request["approval_command"]
    upload = client.post(f"/api/upload-requests/{upload_request['id']}/execute-existing-jarvis", json={"dry_run": True}).json()
    assert upload["ok"] is True
    assert upload["dry_run"] is True
    payload = client.post(f"/api/website/companions/{video_id}/prepare-payload").json()["payload"]
    assert payload["source"]["youtube_video_id"].startswith("dryrun_")
    assert payload["videoUrl"] is None
    assert payload["source"]["website_link_allowed"] is False
