import argparse
import json
import os
import subprocess
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import apimart_cli as cli


class CliTests(unittest.TestCase):
    def test_discovery_covers_full_catalog(self):
        result = cli.list_models()
        self.assertEqual(result["models"], 58)
        self.assertEqual(len(result["items"]), 58)
        self.assertEqual(result["guides"], 174)
        self.assertEqual(result["endpoint_llms_files"], 58)
        self.assertEqual(result["verified_execution_models"], 1)

    def test_discovery_only_model_has_three_guides(self):
        info = cli.model_info("wan-3-0")
        self.assertEqual(info["execution_status"], "discovery_only")
        self.assertEqual(len(info["guides"]), 3)
        self.assertEqual(cli.find_guides("wan-3-0", "pricing")["count"], 1)

    def test_seedance_alias_keeps_verified_execution(self):
        info = cli.model_info("seedance-2.5")
        self.assertEqual(info["execution_status"], "verified")
        self.assertEqual(info["execution_model_id"], "seedance-2.5")

    def test_720p_ten_second_estimate(self):
        result = cli.estimate_cost("720p", 10)
        self.assertEqual(result["estimated_total_usd"], 2.16)

    def test_auto_uses_maximum_hold(self):
        result = cli.estimate_cost("480p", -1)
        self.assertEqual(result["estimate_kind"], "maximum_hold")
        self.assertEqual(result["billable_output_seconds"], 30)

    def test_input_and_output_cost(self):
        result = cli.estimate_cost("1080p", 4, 3)
        self.assertEqual(result["estimated_total_usd"], round(4 * 0.38488 + 3 * 0.22992, 6))

    def test_rejects_4k(self):
        with self.assertRaises(cli.ApiMartError):
            cli.estimate_cost("4k", 5)

    def test_generate_is_dry_run_by_default(self):
        proc = subprocess.run([sys.executable, cli.__file__, "generate", "--prompt", "test", "--duration", "5"], capture_output=True, text=True)
        self.assertEqual(proc.returncode, 0)
        self.assertTrue(json.loads(proc.stdout)["dry_run"])

    def test_payload_reference_cap(self):
        args = argparse.Namespace(resolution="720p", size="adaptive", duration=5, prompt="x", output_format="mp4", silent=False, moderate=False, image_url=["x"] * 31, video_url=[], audio_url=[])
        with self.assertRaises(cli.ApiMartError):
            cli.build_generate_payload(args)


if __name__ == "__main__":
    unittest.main()
