-- ============================================================
-- V013: 운영 도메인 테이블 (단속/계획/배치/AI모델)
-- 백엔드 전용 — 운영자 의사결정 데이터
-- ============================================================

-- ============================================================
-- 단속 이력 (EnforcementHistory 화면)
-- enforcement_records.event_id → prediction_events.id (자동 매칭 + 수동 변경)
-- ============================================================
CREATE TABLE kcg.enforcement_records (
    id                  BIGSERIAL    PRIMARY KEY,
    enf_uid             VARCHAR(50)  UNIQUE NOT NULL,   -- ENF-YYYYMMDD-NNNN
    event_id            BIGINT       REFERENCES kcg.prediction_events(id),
    -- 시간/위치
    enforced_at         TIMESTAMPTZ  NOT NULL,
    zone_code           VARCHAR(30),                    -- zone_polygon_master FK
    area_name           VARCHAR(100),
    lat                 DOUBLE PRECISION,
    lon                 DOUBLE PRECISION,
    -- 대상 선박
    vessel_mmsi         VARCHAR(20),
    vessel_name         VARCHAR(100),
    flag_country        VARCHAR(10),
    -- 단속 내용
    violation_type      VARCHAR(50),                    -- code_master VIOLATION_TYPE 참조
    action              VARCHAR(50)  NOT NULL,          -- code_master ENFORCEMENT_ACTION 참조
    result              VARCHAR(50),                    -- code_master ENFORCEMENT_RESULT 참조
    -- AI 일치도
    ai_match_status     VARCHAR(20),                    -- code_master AI_MATCH 참조
    ai_confidence       NUMERIC(5,4),
    -- 수행 함정
    patrol_ship_id      BIGINT       REFERENCES kcg.patrol_ship_master(ship_id),
    -- 담당
    enforced_by         UUID,
    enforced_by_name    VARCHAR(100),
    remarks             TEXT,
    -- 메타
    created_at          TIMESTAMPTZ  DEFAULT now(),
    updated_at          TIMESTAMPTZ  DEFAULT now()
);

CREATE INDEX idx_enf_date    ON kcg.enforcement_records(enforced_at DESC);
CREATE INDEX idx_enf_event   ON kcg.enforcement_records(event_id);
CREATE INDEX idx_enf_mmsi    ON kcg.enforcement_records(vessel_mmsi);
CREATE INDEX idx_enf_type    ON kcg.enforcement_records(violation_type);

-- ============================================================
-- 단속 계획 (EnforcementPlan 화면)
-- ============================================================
CREATE TABLE kcg.enforcement_plans (
    id                  BIGSERIAL    PRIMARY KEY,
    plan_uid            VARCHAR(50)  UNIQUE NOT NULL,   -- PLN-YYYYMMDD-NNNN
    title               VARCHAR(200) NOT NULL,
    zone_code           VARCHAR(30),
    area_name           VARCHAR(100),
    lat                 DOUBLE PRECISION,
    lon                 DOUBLE PRECISION,
    -- 일정
    planned_date        DATE         NOT NULL,
    planned_from        TIMESTAMPTZ,
    planned_to          TIMESTAMPTZ,
    -- 위험도 평가
    risk_level          VARCHAR(20),
    risk_score          INT,
    -- 배치
    assigned_ship_count INT          DEFAULT 0,
    assigned_crew       INT          DEFAULT 0,
    -- 상태
    status              VARCHAR(20)  DEFAULT 'DRAFT',   -- DRAFT, APPROVED, IN_PROGRESS, COMPLETED, CANCELLED
    alert_status        VARCHAR(20),                    -- 경보 발령 여부
    -- 담당
    created_by          UUID,
    approved_by         UUID,
    remarks             TEXT,
    created_at          TIMESTAMPTZ  DEFAULT now(),
    updated_at          TIMESTAMPTZ  DEFAULT now()
);

CREATE INDEX idx_plan_date   ON kcg.enforcement_plans(planned_date DESC);
CREATE INDEX idx_plan_status ON kcg.enforcement_plans(status);

-- ============================================================
-- 함정 배치 (PatrolRoute, FleetOptimization)
-- ============================================================
CREATE TABLE kcg.patrol_assignments (
    id              BIGSERIAL    PRIMARY KEY,
    ship_id         BIGINT       NOT NULL REFERENCES kcg.patrol_ship_master(ship_id),
    plan_id         BIGINT       REFERENCES kcg.enforcement_plans(id),
    -- 배치 해역
    zone_code       VARCHAR(30),
    -- 기간
    assigned_at     TIMESTAMPTZ  DEFAULT now(),
    completed_at    TIMESTAMPTZ,
    -- 경로
    waypoints       JSONB,                          -- [{lat, lon, name, eta}]
    route_distance_nm NUMERIC(8,2),
    estimated_hours NUMERIC(5,2),
    fuel_estimate_l NUMERIC(10,2),
    -- 상태
    status          VARCHAR(20)  DEFAULT 'ASSIGNED',-- ASSIGNED, EN_ROUTE, ON_STATION, COMPLETED, CANCELLED
    -- 담당
    assigned_by     UUID,
    created_at      TIMESTAMPTZ  DEFAULT now(),
    updated_at      TIMESTAMPTZ  DEFAULT now()
);

CREATE INDEX idx_pa_ship   ON kcg.patrol_assignments(ship_id, assigned_at DESC);
CREATE INDEX idx_pa_plan   ON kcg.patrol_assignments(plan_id);
CREATE INDEX idx_pa_status ON kcg.patrol_assignments(status);

-- ============================================================
-- AI 모델 버전 (AIModelManagement)
-- ============================================================
CREATE TABLE kcg.ai_model_versions (
    id              BIGSERIAL    PRIMARY KEY,
    model_name      VARCHAR(100) NOT NULL,          -- 'gear_classifier', 'risk_scorer', 'parent_inference'
    version         VARCHAR(50)  NOT NULL,
    description     TEXT,
    -- 성능 메트릭
    accuracy_pct    NUMERIC(5,2),
    precision_pct   NUMERIC(5,2),
    recall_pct      NUMERIC(5,2),
    f1_score        NUMERIC(5,4),
    -- 상태
    status          VARCHAR(20)  DEFAULT 'TRAINING', -- TRAINING, EVALUATING, DEPLOYED, ARCHIVED
    deployed_at     TIMESTAMPTZ,
    -- 메타
    train_config    JSONB,
    eval_metrics    JSONB,
    created_by      UUID,
    created_at      TIMESTAMPTZ  DEFAULT now()
);

CREATE TABLE kcg.ai_model_metrics (
    id              BIGSERIAL    PRIMARY KEY,
    model_id        BIGINT       NOT NULL REFERENCES kcg.ai_model_versions(id),
    metric_date     DATE         NOT NULL,
    metric_name     VARCHAR(50)  NOT NULL,          -- accuracy, precision, recall, f1, latency_ms
    metric_value    NUMERIC(10,4),
    metadata        JSONB,
    created_at      TIMESTAMPTZ  DEFAULT now()
);

CREATE INDEX idx_amm_model ON kcg.ai_model_metrics(model_id, metric_date DESC);

-- ============================================================
-- 시드: 단속 이력 6건 (프론트 enforcementStore 기반)
-- ============================================================
INSERT INTO kcg.enforcement_records (enf_uid, enforced_at, zone_code, area_name,
    vessel_mmsi, vessel_name, flag_country, violation_type, action, result,
    ai_match_status, ai_confidence, patrol_ship_id, remarks) VALUES
('ENF-20260403-0001', '2026-04-03 14:30:00+09', 'NLL',               '서해 NLL 인근',
    '412345678', '鲁荣渔56555', 'CN', 'EEZ_VIOLATION', 'CAPTURE', 'PUNISHED',
    'MATCH', 0.95, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='3001'),
    'NLL 인근 불법조업 현행범'),
('ENF-20260402-0001', '2026-04-02 09:15:00+09', 'SPECIAL_FISHING_1', '서해 중부',
    '412345680', '辽大渔42881', 'CN', 'ILLEGAL_GEAR', 'INSPECT', 'WARNED',
    'PARTIAL', 0.72, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='3005'),
    '무허가 선망 사용'),
('ENF-20260401-0001', '2026-04-01 16:45:00+09', 'SPECIAL_FISHING_2', '서해 5도 인근',
    '412345679', '鲁荣渔56556', 'CN', 'DARK_VESSEL', 'TRACK', 'REFERRED',
    'MATCH', 0.88, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='1502'),
    'AIS 차단 후 도주, 수사의뢰'),
('ENF-20260331-0001', '2026-03-31 11:20:00+09', 'EEZ_KR',           'EEZ 남부',
    '412345682', '闽霞渔09876', 'CN', 'ILLEGAL_TRANSSHIP', 'EVIDENCE', 'PUNISHED',
    'MATCH', 0.91, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='5001'),
    '해상 환적 현장 증거 확보'),
('ENF-20260330-0001', '2026-03-30 08:00:00+09', 'WEST_5_ISLANDS',   '연평도 서방',
    '412345681', '浙象渔23166', 'CN', 'ZONE_DEPARTURE', 'DISPERSE', 'RELEASED',
    'MISMATCH', 0.45, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='1502'),
    '조업구역 이탈, 퇴거 조치 (오탐 가능성)'),
('ENF-20260329-0001', '2026-03-29 22:30:00+09', 'NLL',               'NLL 동부',
    '412345683', '苏赣渔05512', 'CN', 'EEZ_VIOLATION', 'CAPTURE', 'PUNISHED',
    'MATCH', 0.97, (SELECT ship_id FROM kcg.patrol_ship_master WHERE ship_code='3001'),
    '야간 EEZ 침범, 고속 도주 후 나포');

-- ============================================================
-- 시드: 이벤트 15건 (프론트 eventStore 기반)
-- ============================================================
INSERT INTO kcg.prediction_events (event_uid, occurred_at, level, category, title, detail,
    vessel_mmsi, vessel_name, area_name, zone_code, lat, lon, speed_kn,
    source_type, ai_confidence, status) VALUES
('EVT-20260407-0001', '2026-04-07 06:12:00+09', 'CRITICAL', 'EEZ_INTRUSION',
    'EEZ 침범 탐지', '중국 어선 鲁荣渔56555 EEZ 침범, 위험도 96',
    '412345678', '鲁荣渔56555', '서해 NLL', 'NLL', 37.52, 124.78, 8.5,
    'VESSEL_ANALYSIS', 0.96, 'IN_PROGRESS'),
('EVT-20260407-0002', '2026-04-07 05:48:00+09', 'HIGH', 'DARK_VESSEL',
    '다크베셀 장기 소실', 'AIS 신호 180분 소실, 완전차단 패턴',
    '412345680', '辽大渔42881', '서해 중부', 'SPECIAL_FISHING_1', 34.85, 125.42, 0.0,
    'VESSEL_ANALYSIS', 0.88, 'ACK'),
('EVT-20260407-0003', '2026-04-07 05:30:00+09', 'HIGH', 'FLEET_CLUSTER',
    '선단 밀집 감지', '중국어선 12척 선단 밀집, 리더 선박 식별',
    '412345681', '浙象渔23166', 'EEZ 북부', 'EEZ_KR', 36.90, 124.20, 6.2,
    'VESSEL_ANALYSIS', 0.82, 'NEW'),
('EVT-20260407-0004', '2026-04-07 04:55:00+09', 'HIGH', 'ILLEGAL_TRANSSHIP',
    '불법환적 의심', '2척 60분 이상 근접 정박, 환적 의심',
    '412345682', '闽霞渔09876', '남해', 'SPECIAL_FISHING_3', 34.42, 129.38, 0.5,
    'VESSEL_ANALYSIS', 0.79, 'NEW'),
('EVT-20260407-0005', '2026-04-07 04:30:00+09', 'CRITICAL', 'MMSI_TAMPERING',
    'MMSI 3회 변경', 'MMSI 변경 3회 탐지, GPS 스푸핑 의심',
    '412345683', '苏赣渔05512', '서해 5도', 'WEST_5_ISLANDS', 37.38, 124.55, 12.3,
    'VESSEL_ANALYSIS', 0.93, 'IN_PROGRESS'),
('EVT-20260407-0006', '2026-04-07 04:10:00+09', 'MEDIUM', 'ZONE_DEPARTURE',
    '구역 이탈', '허가 해역 이탈 감지',
    '440012345', '제주해양호', 'EEZ 남부', 'EEZ_KR', 33.15, 126.58, 5.1,
    'VESSEL_ANALYSIS', 0.65, 'NEW'),
('EVT-20260407-0007', '2026-04-07 03:45:00+09', 'LOW', 'AIS_RESUME',
    'AIS 재송출', 'AIS 신호 회복, 120분 소실 후',
    '412345679', '鲁荣渔56556', '서해 NLL', 'NLL', 37.45, 124.65, 3.2,
    'VESSEL_ANALYSIS', 0.55, 'RESOLVED'),
('EVT-20260407-0008', '2026-04-07 03:20:00+09', 'MEDIUM', 'SPEED_ANOMALY',
    '속력 이상', '급격한 속력 변화 탐지 (2kn → 18kn)',
    '412345678', '鲁荣渔56555', '서해 NLL', 'NLL', 37.50, 124.80, 18.0,
    'VESSEL_ANALYSIS', 0.71, 'ACK'),
('EVT-20260407-0009', '2026-04-07 02:55:00+09', 'HIGH', 'AIS_LOSS',
    'AIS 소실', '45분간 AIS 신호 없음, 간헐송출 패턴',
    '412345681', '浙象渔23166', 'EEZ 북부', 'EEZ_KR', 36.88, 124.18, 0.0,
    'VESSEL_ANALYSIS', 0.75, 'NEW'),
('EVT-20260407-0010', '2026-04-07 02:30:00+09', 'MEDIUM', 'GEAR_ILLEGAL',
    'EEZ 내 어구 설치', '무허가 저층트롤 어구 그룹 탐지',
    '412345680', '辽大渔42881', '서해 중부', 'SPECIAL_FISHING_1', 34.90, 125.40, 2.8,
    'GEAR_GROUP', 0.68, 'NEW'),
('EVT-20260407-0011', '2026-04-07 02:00:00+09', 'MEDIUM', 'FLEET_CLUSTER',
    '어구 그룹 신규 탐지', '4척 어구 그룹 신규 형성',
    NULL, NULL, '서해 5도', 'WEST_5_ISLANDS', 37.40, 124.50, 0.0,
    'GEAR_GROUP', 0.62, 'NEW'),
('EVT-20260407-0012', '2026-04-07 01:30:00+09', 'LOW', 'ZONE_DEPARTURE',
    '접안 후 출항', '검문 대상 선박 출항',
    '412345679', '鲁荣渔56556', '인천항', NULL, 37.45, 126.60, 5.0,
    'VESSEL_ANALYSIS', 0.40, 'RESOLVED'),
('EVT-20260407-0013', '2026-04-07 01:00:00+09', 'CRITICAL', 'EEZ_INTRUSION',
    'NLL 근접 EEZ 침범', '위험도 최상위, 야간 침입',
    '412345683', '苏赣渔05512', 'NLL 동부', 'NLL', 37.55, 124.90, 11.0,
    'VESSEL_ANALYSIS', 0.98, 'RESOLVED'),
('EVT-20260406-0001', '2026-04-06 22:00:00+09', 'HIGH', 'DARK_VESSEL',
    '다크베셀 탐지', 'MMSI 변조 후 AIS 차단',
    '412345682', '闽霞渔09876', '남해', 'SPECIAL_FISHING_3', 34.40, 129.35, 0.0,
    'VESSEL_ANALYSIS', 0.85, 'RESOLVED'),
('EVT-20260406-0002', '2026-04-06 20:30:00+09', 'MEDIUM', 'ILLEGAL_TRANSSHIP',
    '환적 의심', '야간 근접 정박 90분',
    '412345681', '浙象渔23166', 'EEZ 서부', 'EEZ_KR', 35.20, 124.80, 0.3,
    'VESSEL_ANALYSIS', 0.70, 'FALSE_POSITIVE');

-- ============================================================
-- 시드: 단속 계획 5건 (프론트 enforcementStore 기반)
-- ============================================================
INSERT INTO kcg.enforcement_plans (plan_uid, title, zone_code, area_name,
    lat, lon, planned_date, risk_level, risk_score,
    assigned_ship_count, assigned_crew, status, alert_status) VALUES
('PLN-20260408-0001', 'NLL 집중 단속', 'NLL', '서해 NLL', 37.52, 124.78,
    '2026-04-08', 'CRITICAL', 92, 3, 180, 'APPROVED', '경보 발령'),
('PLN-20260409-0001', 'EEZ 북부 순찰', 'EEZ_KR', 'EEZ 북부', 36.90, 124.20,
    '2026-04-09', 'HIGH', 78, 2, 120, 'DRAFT', NULL),
('PLN-20260410-0001', '서해 5도 초계', 'WEST_5_ISLANDS', '서해 5도', 37.38, 124.55,
    '2026-04-10', 'HIGH', 85, 2, 100, 'APPROVED', '주의'),
('PLN-20260411-0001', '남해 환적 감시', 'SPECIAL_FISHING_3', '남해', 34.42, 129.38,
    '2026-04-11', 'MEDIUM', 65, 1, 60, 'DRAFT', NULL),
('PLN-20260412-0001', '서해 중부 야간 작전', 'SPECIAL_FISHING_1', '서해 중부', 34.85, 125.42,
    '2026-04-12', 'HIGH', 80, 2, 140, 'APPROVED', '경보 발령');

-- ============================================================
-- 시드: 일별/월별 통계 (프론트 kpiStore/monthlyTrends 기반)
-- ============================================================
INSERT INTO kcg.prediction_stats_monthly (stat_month, total_detections, total_enforcements,
    by_violation_type, event_count, critical_event_count, false_positive_count, ai_accuracy_pct) VALUES
('2025-10-01', 128, 42, '{"EEZ_VIOLATION":45,"DARK_VESSEL":32,"MMSI_TAMPERING":23,"ILLEGAL_TRANSSHIP":15,"ILLEGAL_GEAR":13}', 85, 12, 16, 81.0),
('2025-11-01', 145, 38, '{"EEZ_VIOLATION":51,"DARK_VESSEL":36,"MMSI_TAMPERING":26,"ILLEGAL_TRANSSHIP":17,"ILLEGAL_GEAR":15}', 97, 15, 14, 84.0),
('2025-12-01', 167, 55, '{"EEZ_VIOLATION":59,"DARK_VESSEL":42,"MMSI_TAMPERING":30,"ILLEGAL_TRANSSHIP":20,"ILLEGAL_GEAR":16}', 112, 18, 12, 86.0),
('2026-01-01', 189, 61, '{"EEZ_VIOLATION":66,"DARK_VESSEL":47,"MMSI_TAMPERING":34,"ILLEGAL_TRANSSHIP":23,"ILLEGAL_GEAR":19}', 126, 22, 10, 88.0),
('2026-02-01', 156, 48, '{"EEZ_VIOLATION":55,"DARK_VESSEL":39,"MMSI_TAMPERING":28,"ILLEGAL_TRANSSHIP":19,"ILLEGAL_GEAR":15}', 104, 17, 9,  89.0),
('2026-03-01', 172, 52, '{"EEZ_VIOLATION":60,"DARK_VESSEL":43,"MMSI_TAMPERING":31,"ILLEGAL_TRANSSHIP":21,"ILLEGAL_GEAR":17}', 115, 19, 8,  90.0),
('2026-04-01', 67,  15, '{"EEZ_VIOLATION":24,"DARK_VESSEL":17,"MMSI_TAMPERING":12,"ILLEGAL_TRANSSHIP":8,"ILLEGAL_GEAR":6}',   45,  8,  2,  93.0);
