package gc.mda.kcg.cctv;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * KHOA CCTV HLS 스트림 프록시
 * CORS 우회를 위해 백엔드에서 KHOA HLS 요청을 중계한다.
 * GET /api/cctv/hls/{site}/{filename}
 */
@RestController
@RequestMapping("/api/cctv")
public class CctvProxyController {

    private static final String KHOA_HLS_BASE =
            "https://www.khoa.go.kr/SEAFOG/m4NiLawsC202gM5ixA7MPTYtO19KmV/hls/khoa";

    private final RestTemplate rest = new RestTemplate();

    @GetMapping("/hls/{site}/{filename}")
    public ResponseEntity<byte[]> proxyHls(
            @PathVariable String site,
            @PathVariable String filename) {

        String url = KHOA_HLS_BASE + "/" + site + "/" + filename;

        HttpHeaders reqHeaders = new HttpHeaders();
        reqHeaders.set("User-Agent", "Mozilla/5.0 (compatible; KCG-Monitor/1.0)");

        ResponseEntity<byte[]> upstream = rest.exchange(
                url, HttpMethod.GET, new HttpEntity<>(reqHeaders), byte[].class);

        HttpHeaders resHeaders = new HttpHeaders();
        if (filename.endsWith(".m3u8")) {
            resHeaders.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
        } else if (filename.endsWith(".ts")) {
            resHeaders.setContentType(MediaType.parseMediaType("video/mp2t"));
        } else {
            resHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        resHeaders.setCacheControl(CacheControl.noCache());

        return new ResponseEntity<>(upstream.getBody(), resHeaders, HttpStatus.OK);
    }
}
